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

Python 将具有多个值的列表转换为字典,python,list,dictionary,Python,List,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.split: lst=[ “3574,A+,2021-03-24”, “3575,O+,2

我有下面的列表,我想把它转换成一个字典,其中每个项目开头的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.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:]表示lst中的v}
打印(输出)
印刷品:

{
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)
输出:

{'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
map
和字典理解

#数据保存您提供的列表
{splitted[0]:splitted[1:]用于在映射中拆分(lambda项:item.split(','),data)}
输出

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']}

建议在代码中添加一些解释。