python: combine values in one column on the basis of ids in another column
Question: I need to combine values in second column of a tab delimited file based on the
ids in first column. The example is given below. What is the fastest way to do
this. I can do it using for loop, going through each line, but I am sure there
is some smart way to do it, which I am not aware of.

    
    
    596230  Other postop infection
    596230  Disseminated candidiasis
    596230  Int inf clstrdium dfcile
    596230  Pressure ulcer, site NOS
    2846079 Schizophrenia NOS-unspec
    7800713 CHF NOS
    7800713 Chr airway obstruct NEC
    7800713 Polymyalgia rheumatica
    7800713 DMII wo cmp nt st uncntr
    

into

    
    
    596230  Other postop infection, Disseminated candidiasis, Int inf clstrdium dfcile, Pressure ulcer, site NOS
    2846079 Schizophrenia NOS-unspec
    7800713 CHF NOS, Chr airway obstruct NEC, Polymyalgia rheumatica, DMII wo cmp nt st uncntr
    


Answer: Assuming you have your text in a file:

    
    
    from collections import defaultdict
    items = defaultdict(list)
    with open("myfile.txt") as infile:
        for line in file:
            id, text = line.rstrip().split("\t")
            items[id].append(text)
    for id in items:
        print id + "\t" + ", ".join(items[id])
    

This does not keep the original order of your `id`s, but it does keep the
order of the texts.

