如何从文件创建字典?

时间:2013-06-17 17:16:04

标签: python python-3.x

我正在尝试编写一个允许我接收文本的Python代码,并逐行读取。在每一行中,单词作为键进入字典,数字应该是指定的值,作为列表。  文件'topics.txt'将由数百行具有相同格式的行组成:

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

等等.. 我需要为每个单词创建词典 对于前: 理想情况下,名称“grain”将是字典中的关键字,值将为dict [grain]:[5,6,..]。 同样, “可可”将是另一个关键,价值观将是 字典[可可]:[1,..] 不多,但到目前为止..

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

2 个答案:

答案 0 :(得分:7)

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 = ...Extended Iterable Unpacking,仅在Python 3.x中可用。

答案 1 :(得分:0)

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