我有给定的清单:
l = ['1,a','2,b','3,c']
我想将此列表转换成字典,像这样:
l_dict = {1:'a',2:'b',3:'c'}
我该如何解决?
您需要先分割,然后再将值推入字典。这里有两个选项,如果您只想按它来决定可以使用list
,否则,如果要按顺序使用od
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)
>>> { int(item.split(',')[0]) : item.split(',')[1] for item in l}
{1: 'a', 2: 'b', 3: 'c'}
您可以使用,
将每个字符串分割为“ str.split
”,然后通过索引获取键和值。