简体   繁体   中英

how to create a dictionary from a file?

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)]

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 which is only available in Python 3.x.

with open("topics.txt", "r") as file:  # Data read from a text file is a string
    dict = {}
    for fullLine in file:
        splitLine = fullLine.split("~")
        num = splitLine[0]
        for name in splitLine[1:]:
            if name in dict:
                dict[name] = dict[name] + (num,)
            else
                dict[name] = (num,)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM