How to Merge Dictionaries in Python
See Python: Tips and Tricks for similar articles.
In Python 3.5, you can merge two or more dictionaries in a single statement by unpacking the new dictionaries into a new dictionary.
- Start with two or more dictionaries:
grades1 = {'Math': 98, 'Science': 87, 'English': 93} grades2 = {'Spanish': 94, 'Gym': 79, 'Science': 91} - Create the merged dictionary using the following syntax:
grades = {**grades1, **grades2}
{'English': 93, 'Gym': 79, 'Math': 98, 'Science': 91, 'Spanish': 94}Before Python 3.5
If you're using an older version of Python, the best way to merge two dictionaries is to create a copy of the first dictionary and then update the copy with the second dictionary:
grades1 = {'Math': 98, 'Science': 87, 'English': 93}
grades2 = {'Spanish': 94, 'Gym': 79, 'Science': 91}
grades = grades1.copy()
grades.update(grades2)Result:{'English': 93, 'Gym': 79, 'Math': 98, 'Science': 91, 'Spanish': 94}Notice that in both cases, when dictionaries being merged have identical keys (e.g., 'Science'), the values from the second dictionary are used in the new merged dictionary.
