How to Merge Dictionaries in Python

  • google plus

In Brief...

In Python 3.5, you can merge two or more dictionaries in a single statement by unpacking the new dictionaries into a new dictionary.

Instructions

  1. Start with two or more dictionaries:
    grades1 = {'Math': 98, 'Science': 87, 'English': 93}
    grades2 = {'Spanish': 94, 'Gym': 79, 'Science': 91}
  2. Create the merged dictionary using the following syntax:
    grades = {**grades1, **grades2}
Result:
{'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.

Related Training

Author: Nat Dunn

Nat Dunn founded Webucator in 2003 to combine his passion for web development with his business expertise and to help companies benefit from both.

Discuss