我如何将文本列表转换成字典?

问题描述 投票:0回答:2

我有给定的清单:

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

我想将此列表转换成字典,像这样:

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

我该如何解决?

list dictionary python-3.6
2个回答
0
投票

您需要先分割,然后再将值推入字典。这里有两个选项,如果您只想按它来决定可以使用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)


0
投票
>>> { int(item.split(',')[0]) : item.split(',')[1] for item in l}
{1: 'a', 2: 'b', 3: 'c'}

您可以使用,将每个字符串分割为“ str.split”,然后通过索引获取键和值。

© www.soinside.com 2019 - 2024. All rights reserved.