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.

Take our Introduction to Python Training course for free.

See the Course Outline and Register

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.

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, XML, Windows, Java, Adobe, HTML5, JavaScript, Angular, and much more. Check out our complete course catalog.

Categories

Courses

Author: Nat Dunn

Nat Dunn founded Webucator in 2003 to combine his passion for technical training with his business expertise and to help companies benefit from both. His previous experience was in sales, business and technical training, and management. Nat has an MBA from Harvard Business School and a BA in International Relations from Pomona College.

Discuss