jas jas - 1 year ago 69
Python Question

How to make a new dict from two dict

I'm trying to build a new dict from dict of just keys and a another dict of keys values pairs. In the second dict there could be more then one item mapped to same key. In the new dict, I would like to collect all those items together in a list and map it to a key. I have this code so far but it doesn't work. I get

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:

print result_dict

I'm expecting to build a dict like this:

'1': ['Badgis', 'Badakhshan'],
'2': ['Berat', 'Bulqize'],
'3': ['Ayn Tamushanat', 'Ayn Daflah'],
'4': ["Manu'a", 'Eastern'],
'5': ['Canillo', 'Andorra la Vella']

Answer Source

Use a list of tuples instead:

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

Then do something like this:

dictionary = {}

for (key, val) in result:
    if not key in dictionary:
          dictionary[key] = [val]
        dictionary[key] = dictionary[key] + [val]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download