how to create a dictionary from a file?
Question: I'm trying to write a Python code that will allow me to take in text, and read
it line by line. In each line, the words just go into the dictionary as a key
and the numbers should be the assigned values, as a list. the file
'topics.txt' will be composed of hundreds of lines that have the same format
as this:

    
    
    1~cocoa
    2~
    3~
    4~
    5~grain~wheat~corn~barley~oat~sorghum
    6~veg-oil~linseed~lin-oil~soy-oil~sun-oil~soybean~oilseed~corn~sunseed~grain~sorghum~wheat
    7~
    8~
    9~earn
    10~acq
    

and so on.. i need to create dictionaries for each word for ex: Ideally, the
name "grain" would be a key in the dictionary, and the values would be
dict[grain]: [5,6,..]. similarly, "cocoa" would be another key and values
would be dict[cocoa]:[1,..] Not much,but so far..

    
    
    with open("topics.txt", "r") as fi:  # Data read from a text file is a string
        d = {}
        for i in fi.readlines():
            temp = i.split()
            #i am lost here
            num = temp[0]
            d[name] = [map(int, num)]
    


Answer: <http://docs.python.org/3/library/collections.html#collections.defaultdict>

    
    
    import collections
    
    with open('topics.txt') as f:
        d = collections.defaultdict(list)
        for line in f:
            value, *keys = line.strip().split('~')
            for key in filter(None, keys):
                d[key].append(value)
    

`value, *keys = ...` is [Extended Iterable
Unpacking](http://www.python.org/dev/peps/pep-3132/) which is only available
in Python 3.x.

