将文本列表转换为字典?

Convert text list into Dictionary?

我有一个给定的列表:

l = ['1,a','2,b','3,c']

我想把这个列表转换成字典,像这样:

l_dict = {1:'a',2:'b',3:'c'}

我该如何解决?

需要先拆分,再将值压入dict。这里有两个选项,如果你只是想把它推到 dict 你可以使用 list 否则如果你想按顺序使用 od

Link

from collections import OrderedDict

l = ['1,a','2,b','3,c']

list = {}
od = OrderedDict() 

for text in l:
    convertToDict = text.split(",")
    list[convertToDict[0]] = convertToDict[1]
    od[convertToDict[0]] = convertToDict[1]


print(list)
print(od)

您可以使用 generator expression to pass to the dict 构造函数将每个字符串拆分为 ','

dict(e.split(',') for e in l)

输出:

{'1': 'a', '2': 'b', '3': 'c'}