how to merge file lines having the same first word in python?
Question: I have written a program to merge lines in a file containing the same first
word in python.However I am unable to get the desired output. Can anyone
please suggest me the mistake in my program?

**Note:- (line1,line 2)** and **(line4,line5,line6)** are merging since they
have the same first element

    
    
    #input
    "file.txt"
    line1: a b c
    line2: a b1 c1
    line3: d e f
    line4: i j k
    line5: i s t 
    line6: i m n 
    
    #output
    a b c a b1 c1 
    d e f
    i j k i s t i m n 
    
    #my code
    for i in range(0,len(a)):
    j=i
    try:
        while True:
            if  a[j][0] == a[j+1][0]:
                L.append(a[j])
                L.append(a[j+1])
                j=j+2
            else:
                print a[i]
                print L
                break
    except:
        pass`
    


Answer: Try this (give it the file as an argument).

Produces a dictionary with the lines you expect.

    
    
    import sys
    if "__main__" == __name__:
    
    
        new_lines = dict()
        # start reading file
        with open(sys.argv[1]) as a:
    
            # iterate file by lines - removing newlines
            for a_line in a.read().splitlines():
    
                # candidate is first word in every sentence
                candidate = a_line.split()[0] # split on whitespace by default
    
                # dictionary keys are previous candidates
                if candidate in new_lines.keys():
    
                    # word already included
                    old_line = new_lines[candidate]
                    new_lines[candidate] = "%s %s" % (old_line, a_line)
    
                else:
    
                    # word not included
                    new_lines[candidate] = a_line
    
    
    # now we have our dictionary. print it (or do what you want with it)
    for key in new_lines.keys():
        print "%s -> %s" % (key, new_lines[key])
    

output:

    
    
    a -> a b c a b1 c1
    i -> i j k i s t i m n
    d -> d e f
    

