繁体   English   中英

将具有多个值的列表转换为字典

[英]Converting a list with multiple values into a dictionary

我有以下列表,我想将其转换为字典,其中每个项目开头的 4 位值成为 id。

['3574,A+,2021-03-24', '3575,O+,2021-04-03', '3576,AB-,2021-04-09', '3580,AB+,2021-04-27', '3589,A+,2021-05-08', '3590,B-,2021-05-11']

我尝试了许多不同的方法,但似乎不起作用。

您可以使用str.splitmap和字典理解

# data holds the list you have provided
{splitted[0]:splitted[1:] for splitted in map(lambda item:item.split(','), data)}

OUTPUT

Out[35]: 
{'3574': ['A+', '2021-03-24'],
 '3575': ['O+', '2021-04-03'],
 '3576': ['AB-', '2021-04-09'],
 '3580': ['AB+', '2021-04-27'],
 '3589': ['A+', '2021-05-08'],
 '3590': ['B-', '2021-05-11']}

您可以将字典理解与str.split一起使用:

lst = [
    "3574,A+,2021-03-24",
    "3575,O+,2021-04-03",
    "3576,AB-,2021-04-09",
    "3580,AB+,2021-04-27",
    "3589,A+,2021-05-08",
    "3590,B-,2021-05-11",
]

out = {int(v.split(",")[0]): v.split(",")[1:] for v in lst}
print(out)

印刷:

{
    3574: ["A+", "2021-03-24"],
    3575: ["O+", "2021-04-03"],
    3576: ["AB-", "2021-04-09"],
    3580: ["AB+", "2021-04-27"],
    3589: ["A+", "2021-05-08"],
    3590: ["B-", "2021-05-11"],
}

这是执行我认为您要求的代码的代码。 我还在代码中添加了注释以进行更多说明。

my_list = ['3574,A+,2021-03-24',
       '3575,O+,2021-04-03',
       '3576,AB-,2021-04-09',
       '3580,AB+,2021-04-27',
       '3589,A+,2021-05-08',
       '3590,B-,2021-05-11']#your list
my_dict = {}#The dictionary you want to put the list into

print("Your list:", my_list, "\n")

for item in my_list:#cycles through every item in your list  
    ID, value = item.split(",", 1)#Splits the item in your list only once (when it sees the first comma)
    print(ID + ": " + value)
    my_dict[ID] = value#Add the ID and value to your dictionary

print("\n" + "Your desired dictionary:", my_dict)

哪个输出:

Your list: ['3574,A+,2021-03-24', '3575,O+,2021-04-03', '3576,AB-,2021-04-09', '3580,AB+,2021-04-27', '3589,A+,2021-05-08', '3590,B-,2021-05-11'] 

3574: A+,2021-03-24
3575: O+,2021-04-03
3576: AB-,2021-04-09
3580: AB+,2021-04-27
3589: A+,2021-05-08
3590: B-,2021-05-11

Your desired dictionary: {'3574': 'A+,2021-03-24', '3575': 'O+,2021-04-03', '3576': 'AB-,2021-04-09', '3580': 'AB+,2021-04-27', '3589': 'A+,2021-05-08', '3590': 'B-,2021-05-11'}

享受!

尝试:

result = dict(i.split(',', 1) for i in lst)

OUTPUT:

{'3574': 'A+,2021-03-24',
 '3575': 'O+,2021-04-03',
 '3576': 'AB-,2021-04-09',
 '3580': 'AB+,2021-04-27',
 '3589': 'A+,2021-05-08',
 '3590': 'B-,2021-05-11'}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM