如何从两个词典中制作一个新的词典

时间:2016-06-22 20:30:46

标签: python dictionary

我试图从只是键的dict和另一个键值对的dict构建一个新的dict。在第二个字典中,可能有多个项目映射到相同的键。在新的词典中,我想在列表中收集所有这些项目并将其映射到一个键。到目前为止我有这个代码,但它不起作用。我得到public class ProgramController : CustomBaseController { // GET: Program public ActionResult Index() { // db is not accessible here for some reason, // like it wasn't inherited from CustomBaseController var user = db.getUserByID(1); return List(user); } ...

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

1 个答案:

答案 0 :(得分:0)

改为使用元组列表:

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]