![](/img/trans.png)
[英]Turning a Python dict with mutiple values in to a list with every key value pair
[英]Turning list into dictionary where list value is dict key and value
我有一个包含长字符串的列表,一个数字,然后是一个“句子”,比如说。 我想知道是否有办法把它变成字典,数字是值
mylist = ['8 red cars', '3 blue cars', '11 black cars']
那是我的清单,我希望字典是:
{
'red cars': 8
'blue cars': 3
'black cars': 11
}
我相信有更好的方法,但下面的代码适用于您的示例。
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)
[编辑]:因为问题已编辑。 (反转KEY、VALUE的位置)
mylist = ['8 red cars', '3 blue cars', '11 black cars', '1 yellow car', '1 silver car', '22 blue vans', '11 green cars', '11 black vans', '4 white cars']
split_list=[i.split(' ', 1) for i in mylist]
flat_list = []
for sublist in split_list:
flat_list.extend(sublist)
dict= {flat_list[i+1]: int(flat_list[i]) for i in range(0, len(flat_list), 2)}
print(dict)
[结果]:
dict={ 'red cars': 8, 'blue cars': 3, 'black cars': 11, 'yellow car': 1, 'silver car': 1, 'blue vans': 22, 'green cars': 11, 'black vans': 11, 'white cars': 4 }
以前的所有方法都是完全有效的,但我要投入两分钱:
d = {}
for x in ['8 red cars', '3 blue cars', '11 black cars']:
[k, v] = x.split(' ', 1) # ['8', 'red cars']
d[int(k)] = v
print(d) # {8: 'red cars', 3: 'blue cars', 11: 'black cars'}
显然你已经更新了你的问题,所以这里是相应的答案:
d = {}
for x in ['8 red cars', '3 blue cars', '11 black cars']:
[k, v] = x.split(' ', 1) # ['8', 'red cars']
d[v] = int(k)
print(d) # {'red cars': 8, 'blue cars': 3, 'black cars': 11}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.