如何用两个di来做一个新dict

2024-09-28 23:41:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着从只包含键的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']    
}

Tags: keyresultdictlaeasternmanuandorraberat
1条回答
网友
1楼 · 发布于 2024-09-28 23:41:22

改用元组列表:

result = [('2', 'Berat'), ('3', 'Ayn Daflah'), ('4', 'Eastern'), ('5', 'Canillo'), ('1', 'Badgis'), ('4', "Manu'a"), etc. ]

然后这样做:

dictionary = {}

for (key, val) in result:
    if not key in dictionary:
          dictionary[key] = [val]
    else:
        dictionary[key] = dictionary[key] + [val]

相关问题 更多 >