如何在文件中用Python创建Dictionary,其中值是列表

时间:2016-05-17 08:06:14

标签: python dictionary

我有一个txt文件,我想将值读入字典。与普通字典不同,每个key的值是一个值对,例如:

tiger eat meat
tiger eat people
rabbit eat carrot
people can walk
trees has root
people has hand

我想要一本字典,

tiger, {eat, meat}, {eat, people}
rabbit, {eat, carrot}
trees, {has, root}
people, {can, walk}, {has, hand}

我应该read linessplit(\n)分为3个项目并将第一个存储为密钥,其余两个存储为值吗?或者有更好的方法来存储这两个值?

我的目标是,当我查询老虎吃什么时,我想得到答案meatpeople

5 个答案:

答案 0 :(得分:3)

import collections

lines=[]
with open('data1', 'r') as f:
    lines=list(map(lambda line:line.strip(), f.readlines()))

d, flag=collections.defaultdict(list), False
for line in lines:
    temp=list(map(lambda x:x.strip(), line.split()))
    d[temp[0]].append(temp[1:])
print(d)

这是输出:

$ cat data1
tiger eat meat
tiger eat people
rabbit eat carrot
people can walk
trees has root
people has hand
$ python3 a.py 
defaultdict(<class 'list'>, {'rabbit': [['eat', 'carrot']], 'trees': [['has', 'root']], 'tiger': [['eat', 'meat'], ['eat', 'people']], 'people': [['can', 'walk'], ['has', 'hand']]})

如果你想要这个结构:

$ python3 a.py 
defaultdict(<class 'list'>, {'people': [{'can': 'walk'}, {'has': 'hand'}], 'tiger': [{'eat': 'meat'}, {'eat': 'people'}], 'trees': [{'has': 'root'}], 'rabbit': [{'eat': 'carrot'}]})

将脚本中的第二行替换为:

d[temp[0]].append({temp[1]:temp[2]})

答案 1 :(得分:1)

首先,您可以根据主题和动词累积数据,例如

data = {}
with open("Input.txt") as fin:
    for line in fin:
        subject, verb, obj = line.strip().split()
        data.setdefault(subject, {}).setdefault(verb, []).append(obj)

现在,data将如下所示

{'people': {'can': ['walk'], 'has': ['hand']},
 'rabbit': {'eat': ['carrot']},
 'tiger': {'eat': ['meat', 'people']},
 'trees': {'has': ['root']}}

我们基本上已经创建了嵌套字典,其值为列表。

现在,只需按照您喜欢的方式迭代和打印结果就可以了。

for subject in data:
    print subject,
    for verb in data[subject]:
        for obj in data[subject][verb]:
            print "{{{}, {}}}".format(verb, obj),
    print

<强>输出

tiger {eat, meat} {eat, people}
trees {has, root}
rabbit {eat, carrot}
people {has, hand} {can, walk}

注意:如果数据的原始顺序很重要,那么您可以使用collections.OrderedDict,而不是使用普通词典,就像这样

from collections import OrderedDict


data = OrderedDict()
with open("Input.txt") as fin:
    for line in fin:
        subject, verb, obj = line.strip().split()
        data.setdefault(subject, OrderedDict()).setdefault(verb, []).append(obj)

答案 2 :(得分:1)

创建一个字典,其键是主题,其值是包含字典的列表,其中动词作为键,对象作为值(参见结果)。

animal_attr = {} #Don't mind the name :)
with open (filename,"r") as f:
    for line in f:
        items = line.split()
        if items[0] not in animal_attr.keys():
            animal_attr[items[0]] = []            
        animal_attr[items[0]].append({items[1]: items[2]})

print(animal_attr)
#{'tiger': [{'eat': 'meat'}, {'eat': 'people'}], 'trees': [{'has': 'root'}],
# 'rabbit': [{'eat': 'carrot'}], 'people': [{'can': 'walk'}, {'has': 'hand'}]}

答案 3 :(得分:0)

有一次,您已经阅读了文件中的行,您可以为此目的创建nested defaultdict

d = defaultdict(lambda: defaultdict(list))

for line in lines:
    words = line.split()
    d[words[0]][words[1]].append(words[2])

如果您print(d),您将获得以下信息:

defaultdict(<function <lambda> at 0x7fa858444320>, {'tiger': defaultdict(<type 'list'>, {'eat': ['meat', 'people'], 'eats': []}), 'trees': defaultdict(<type 'list'>, {'has': ['root']}), 'rabbit': defaultdict(<type 'list'>, {'eat': ['carrot']}), 'people': defaultdict(<type 'list'>, {'has': ['hand'], 'can': ['walk']})})

并且,您可以访问以下老虎吃的东西:

>>> d['tiger']['eat']
['meat', 'people']

如果,您想查看people可以做的事情:

>>> d['people']['can']
['walk']

答案 4 :(得分:0)

import collections

d=collections.defaultdict(list)
with open('text.txt', 'r') as lines:
    for line in lines:
        temp=line.split()
        d[temp[0]].append({temp[1]: temp[2]})
print(d)

输出:

defaultdict(<type 'list'>, {'tiger': [{'eat': 'meat'}, {'eat': 'people'}], 'trees': [{'has': 'root'}], 'rabbit': [{'eat': 'carrot'}], 'people': [{'can': 'walk'}, {'has': 'hand'}]})