将列表转换为字典(python)

时间:2014-12-09 04:47:19

标签: python-3.x

问题:

names = ['Edogawa, Conan, 100', 'Kaitu, kid, 90', 'Mouri, Ran, 70']

我需要将这些信息存储在这样的字典中:

{'Edogawa Conan': 100, 'Kaitu kid': 90, 'Mouri Ran:' 70}

我尝试过这段代码,但它太长而且效率不高。

names1 = names[0].split(',')
names2 = names[1].split(',')
names3 = names[2].split(',')

names_dict = {}

names_dict[names1[0] + ' ' + names1[1]]= int(names1[2])
names_dict[names2[0] + ' ' + names2[1]]= int(names2[2])
names_dict[names3[0] + ' ' + names3[1]]= int(names2[2])

1 个答案:

答案 0 :(得分:0)

>>> dict((x + y, int(z)) for (x, y, z) in (w.split(',') for w in ['Edogawa, Conan, 100', 'Kaitu, kid, 90', 'Mouri, Ran, 70']))
{'Mouri Ran': 70, 'Edogawa Conan': 100, 'Kaitu kid': 90}