我有一个 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}
我是否应该只读取行
,拆分(\n)
为3 个项目并将第一个存储为键,将其余两个存储为值?或者有更好的方法来存储这两个值?
我的目标是,当我查询老虎吃什么时,我想得到答案 meat
和 people
。
最佳答案
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]})
关于python - 如何从文件在 Python 中创建字典,其中值是一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37270480/