我试着从只包含键的dict和另一个包含键-值对的dict构建一个新dict。在第二个dict中,可以有多个条目映射到同一个键。在新的dict中,我想将所有这些项收集在一个列表中,并将其映射到一个键。我有这个代码,但它不工作。我得到KeyError: '1'
。你知道吗
dictKeys = ['1', '2', '3', '4', '5']
#dict to sort based on dictKeys
result = {'2': 'Berat',
'3': 'Ayn Daflah',
'4': 'Eastern',
'5': 'Canillo',
'1': 'Badgis',
'4': "Manu'a",
'5': 'Andorra la Vella',
'1': 'Badakhshan',
'2': 'Bulqize',
'3': 'Ayn Tamushanat'}
#expected dictonary
result_dict = {}
for k in dictKeys:
for key,value in result.items():
if k == key:
result_dict[key].append(value)
print result_dict
我希望建立一个这样的dict:
{
'1': ['Badgis', 'Badakhshan'],
'2': ['Berat', 'Bulqize'],
'3': ['Ayn Tamushanat', 'Ayn Daflah'],
'4': ["Manu'a", 'Eastern'],
'5': ['Canillo', 'Andorra la Vella']
}
改用元组列表:
然后这样做:
相关问题 更多 >
编程相关推荐