python - 如何从文件在 Python 中创建字典,其中值是一个列表

标签 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}

我是否应该只读取行拆分(\n) 为3 个项目并将第一个存储为键,将其余两个存储为值?或者有更好的方法来存储这两个值?

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

最佳答案

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/

相关文章:

python - 根据键对字典中的值取平均值

java - 如何在 Java 8 中将 Map<Shape, int[]> 转换为 Map<Shape, Set<Integer>>?

python - 将字符串 '\u05d9\u05d7\u05e4\u05d9\u05dd' 转换为其在 python 中的 unicode 字符

python - 详细记录 Django 测试

javascript - 如何在 JSON 映射(在 JavaScript 中)中指定键的值?

python - 将字典中最大的 2 个键和值放入另一个字典中

python:遍历列表并用相应的字典值替换元素

python - Flask:如何在应用程序根目录中读取文件?

python - 从 CSV 文件创建字典

python - 子类化方法显示虚拟环境中站点包中的错误