将列表变成字典

时间:2019-04-05 17:34:42

标签: python python-3.x

我知道这个问题已经被问了一百万遍了,但是我很难为我的问题找出解决之道。

这是我的代码:

try:
    dict1={}
    main_list = [line.rstrip() for line in open("food01.csv")]
    print(main_list)
except IOError:
    print("Error opening file")

文件(CSV)的输出:

['lion,gazelle', 'jackal,grass,zebra,gazelle', 'gazelle,grass,acacia leaves', 'zebra,grass']

我想要的是这样的列表字典:

{'lion':['gazelle'],'jackal':['grass,zebra,gazelle'],'gazelle':['grass,acacia leaves'],'zebra':['grass']}

3 个答案:

答案 0 :(得分:6)

您可以像这样使用嵌套的dict理解:

{first: rest for cols in rows for first, *rest in (cols.split(','),)}

所以给定:

rows = ['lion,gazelle', 'jackal,grass,zebra,gazelle', 'gazelle,grass,acacia leaves', 'zebra,grass']

这将返回:

{'lion': ['gazelle'], 'jackal': ['grass', 'zebra', 'gazelle'], 'gazelle': ['grass', 'acacia leaves'], 'zebra': ['grass']}

答案 1 :(得分:1)

这应该做到。

lst = ['lion,gazelle', 'jackal,grass,zebra,gazelle', 'gazelle,grass,acacia leaves', 'zebra,grass']

dct = {}
for l in lst:
    items = l.split(',')
    dct[items[0]] = items[1:]

print(dct)
#{'lion': ['gazelle'], 'jackal': ['grass', 'zebra', 'gazelle'], 'gazelle': ['grass', 'acacia leaves'], 'zebra': ['grass']}

答案 2 :(得分:0)

您需要为此提供2个列表。 1表示键1表示值 尝试将捕食者和猎物分成2个列表,然后使用zip将它们组合成字典

keys = ["lion", "jackal", 'gazelle']
values = [["gazelle"], ["grass, zebra, gazelle"], ["grass, acacia leaves"]]
dict1 = dict(zip(keys, values))
print(dict1)