python-3.x - 将食物网文本文件转换成字典-python 3
问题描述
我怎样才能把文件变成字典?
我必须将食物网络文件中的所有数据加载到描述吃关系的字典中。字典中的键将由捕食者的名称(这是第一个元素)。字典中的值将是列表,其中列表中的每个元素都是捕食者吃掉的猎物的名称。
Goat,Plants
Jackal,Goat,Rabbit
Kite,Snake,Mouse
Lion,Goat,Jackal,Wild Cat
Mouse,Plants
Owl,Mouse
Rabbit,Plants
Snake,Mouse
Wild Cat,Rabbit,Mouse
输出应如下所示:
Predators and Prey:
Goat eats Plants
Jackal eats Goat and Rabbit
Kite eats Mouse and Snake
Lion eats Goat, Jackal and Wild Cat
Mouse eats Plants
Owl eats Mouse
Rabbit eats Plants
Snake eats Mouse
Wild Cat eats Mouse and Rabbit
解决方案
如果文本文件是'dictionary.txt'-
dic = dict()
with open('dictionary.txt', 'r') as f:
for line in f.readlines():
words = line.strip().split(',')
dic[words[0]] = [words[1:]]
推荐阅读
- c++ - 将使用 bitset 转换的二进制数放入向量中
- pandas - Pandas Pivot 多个日期列
- r - R:按ID计算特定日期之前的天数
- recursion - cudaErrorIllegalInstruction 递归函数调用
- java - Java 弹簧安全。记录的用户信息
- java - 为什么它给我一个“不幸
已结束”当我在外部设备上运行应用程序时 - html - 如何将wordpress页面转换为普通的html页面?
- java - 有没有办法合法地投射 Mockito 模拟对象?
- react-navigation - ReactNative 导航 5 - 如何获取 `navigation.state.params`(从 1.x 升级)
- php - Google Ads API - 从电子邮件地址获取 customerId