首页 > 解决方案 > 将列表转换为字典,其中列表值为字典键和值

问题描述

我有一个包含长字符串的列表,一个数字,然后是一个“句子”,比如说。我想知道是否有办法把它变成字典,数字是值

mylist = ['8 red cars', '3 blue cars', '11 black cars']

那是我的清单,我希望字典是:

{
 'red cars': 8
 'blue cars': 3
 'black cars': 11
}

标签: pythonlistdictionary

解决方案


我相信有更好的方法,但下面的代码适用于您的示例。

mylist = ['8 red cars', '3 blue cars', '11 black cars']
car_dict = {}

for item in mylist:
    number = [int(s) for s in item.split() if s.isdigit()][0]
    words = [str(s) for s in item.split() if s.isalpha()]
    car_dict[number] = ' '.join(words)
    
print(car_dict)

推荐阅读