appending a list from a read text file python3
Question: I am attempting to read a txt file and create a dictionary from the text. a
sample txt file is:

    
    
    John likes Steak
    
    John likes Soda
    
    John likes Cake
    
    Jane likes Soda
    
    Jane likes Cake
    
    Jim likes Steak
    

My desired output is a dictionary with the name as the key, and the "likes" as
a list of the respective values:

    
    
    {'John':('Steak', 'Soda', 'Cake'), 'Jane':('Soda', 'Cake'), 'Jim':('Steak')}
    

I continue to run into the error of adding my stripped word to my list and
have tried a few different ways:

    
    
    pred = ()
    
    prey = ()
    
    spacedLine = inf.readline()
    
    line = spacedLine.rstrip('\n')
    
    while line!= "":
    
        line = line.split()
        pred.append = (line[0])
        prey.append = (line[2])
        spacedLine = inf.readline()
        line = spacedLine.rstrip('\n')
    

and also:

spacedLine = inf.readline()

    
    
    line = spacedLine.rstrip('\n')
    
    while line!= "":
    
         line = line.split()      
         if line[0] in chain:
           chain[line[0] = [0, line[2]]
          else:
            chain[line[0]] = line[2]
        spacedLine = inf.readline()
        line = spacedLine.rstrip('\n')
    

any ideas?


Answer: This will do it (without needing to read the entire file into memory first):

    
    
    likes = {}
    for who, _, what in (line.split()
                            for line in (line.strip()
                                for line in open('likes.txt', 'rt'))):
        likes.setdefault(who, []).append(what)
    
    print(likes)
    

Output:

    
    
    {'Jane': ['Soda', 'Cake'], 'John': ['Steak', 'Soda', 'Cake'], 'Jim': ['Steak']}
    

Alternatively, to simplify things slightly you could use a
temporary`collections.defaultdict`:

    
    
    from collections import defaultdict
    
    likes = defaultdict(list)
    for who, _, what in (line.split()
                            for line in (line.strip()
                                for line in open('likes.txt', 'rt'))):
        likes[who].append(what)
    
    print(dict(likes))  # convert to plain dictionary and print
    

