首页 > 解决方案 > 将食物网文本文件转换成字典-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

标签: python-3.x

解决方案


如果文本文件是'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:]]

推荐阅读