Merging Dictionaries Python


Hey guys i want to merge these 45 dictionaries into one. they all have the same keys.

d1 = {'Image': '', 'Stadium': 'Westfalenstadion', 'Capacity': '81,365', 'City': 'Dortmund', 'Population': '586,852', 'Postal Code': '44001-44388', 'State': 'North Rhine-Westphalia', 'Home Team': 'Borussia Dortmund', 'Opened Year': '1974', 'Notes': 'UEFA Category 4 stadium'}
d2 = {'Image': '', 'Stadium': 'Allianz Arena', 'Capacity': '75,000', 'City': 'Munich', 'Population': '1,487,708', 'Postal Code': '80331–81929', 'State': 'Bavaria', 'Home Team': 'FC Bayern Munich', 'Opened Year': '2005', 'Notes': 'UEFA Category 4 stadium'}
d3 = {'Image': '', 'Stadium': 'Olympiastadion Berlin', 'Capacity': '74,475', 'City': 'Berlin', 'Population': '3,677,472', 'Postal Code': '', 'State': 'Berlin', 'Home Team': 'Hertha BSC', 'Opened Year': '1936', 'Notes': 'UEFA Category 4 stadium'}
d4 = {'Image': '', 'Stadium': 'Olympiastadion Munich', 'Capacity': '69,250', 'City': 'Munich', 'Population': '1,487,708', 'Postal Code': '80331–81929', 'State': 'Bavaria', 'Home Team': 'Various', 'Opened Year': '1972', 'Notes': ''}
d5 = {'Image': '', 'Stadium': 'Veltins-Arena', 'Capacity': '62,271', 'City': 'Gelsenkirchen', 'Population': '', 'Postal Code': '45801-45899', 'State': 'North Rhine-Westphalia', 'Home Team': 'FC Schalke 04', 'Opened Year': '2001', 'Notes': 'UEFA Category 4 stadium'}
d6 = {'Image': '', 'Stadium': 'Mercedes-Benz Arena', 'Capacity': '60,469', 'City': 'Stuttgart', 'Population': '626,275', 'Postal Code': '70173–70619', 'State': 'Baden-Württemberg', 'Home Team': 'VfB Stuttgart', 'Opened Year': '1933', 'Notes': 'UEFA Category 4 stadium'}

I tried it with defaultdict and update but it didnt work.

Asked By: Pablo



If I got you right, do the following:

from collections import defaultdict

merged = defaultdict(list)
for d in [d1, d2, d3...]:
    for key, value in d.items():
Answered By: ekon
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.