TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Merge Dictionaries in Python
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

Merge Dictionaries in Python

Last updated: Apr 23, 2024 3:01 pm
By Meenakshi Agarwal
Share
11 Min Read
How to Merge Dictionaries in Python
How to Merge Dictionaries in Python
SHARE

In this post, we are describing different ways to merge dictionaries in Python. Some of the methods need a few lines of code to merge while some can combine dictionaries in a single expression.

Contents
Different Ways to Merge Two DictionariesBy updating cumulativelyBy using the unpacking operatorCombine Two or More DictionariesMerge Using Custom Action

How to Merge Dictionaries in Python

There is no built-in method to combine dictionaries, but we can make some arrangements to do that. The few options that we’ll use are the dictionary’s update method and Python 3.5’s dictionary unpacking operator also known as **kwargs.

You need to be decisive in selecting which of the solutions suits your condition the best. So, let’s now step up to see the different options to solve our problem.

A Must Read: Python Dictionary | Create, Update, Append

How to Merge Dictionaries in Python
How to Merge Dictionaries in Python

Before we jump on the solutions, let’s define our problem statement first.

Different Ways to Merge Two Dictionaries

Let’s demonstrate the different methods to merge dictionaries in Python. For this purpose, we’ll utilize the following data.

We have two dictionaries representing two BUs (business units) of an IT company. Both include their employee names as keys along with the work ex as values. You can see the structure below.

Business Unit = { Employee Name: Work Experience, ...}

Here are two dictionaries with some sample data that we need to merge.

unitFirst = { 'Joshua': 10, 'Ryan':5, 'Sally':20, 'Martha':17, 'Aryan':15}
unitSecond = { 'Versha': 11, 'Tomi':7, 'Kelly':12, 'Martha':24, 'Barter':9}

The company has also set some goals for merging dictionaries, actually the business units.

  • If employee names are duplicates, then unit2 values should override the unit1.
  • Both units must have valid keys.
  • Both units must have valid integer values.
  • Creating a new dictionary should not lead to any changes in the original two.
  • Any modification in the new dictionary should not impact the data inunit1 and unit2.

Let’s now go through the given methods for merging dictionaries and choose which fits best in your case.

By updating cumulatively

The most obvious way to combine the given dictionaries is to call the update() method for each unit. Since we’ve to keep the unit2 values in case of duplicates, we should update it last.

Please note that we can merge even more than two dictionaries using this approach.

Here is the sample code to merge two dictionaries:

"""
Desc:
  Python program to combine two dictionaries using update()
"""
# Define two existing business units as Python dictionaries
unitFirst = { 'Joshua': 10, 'Ryan':5, 'Sally':20, 'Martha':17, 'Aryan':15}
unitSecond = { 'Versha': 11, 'Tomi':7, 'Kelly':12, 'Martha':24, 'Barter':9}

# Initialize the dictionary for the new business unit
unitThird = {}
# Update the unitFirst and then unitSecond
unitThird.update(unitFirst)
unitThird.update(unitSecond)

# Print new business unit
# Also, check if unitSecond values overrided the unitFirst values or not
print("Unit Third: ", unitThird)
print("Unit First: ", unitFirst)
print("Unit Second: ", unitSecond)

Running the above code gives the following result:

Unit Third: {'Kelly': 12, 'Ryan': 5, 'Joshua': 10, 'Barter': 9, 'Tomi': 7, 'Aryan': 15, 'Sally': 20, 'Martha': 24, 'Versha': 11}
Unit First: {'Sally': 20, 'Ryan': 5, 'Joshua': 10, 'Aryan': 15, 'Martha': 17}
Unit Second: {'Tomi': 7, 'Kelly': 12, 'Barter': 9, 'Versha': 11, 'Martha': 24}

You can see that the new unit retained an employee named Martha with a value (24) from the second unit. However, the new dictionary has combined all other elements from the two input dictionaries.

Moreover, we first created a new dictionary to keep the merged output of the other two dictionaries. It’ll make sure that changing the new one won’t affect the values of the original containers.

By using the unpacking operator

In Python 3.5 or above, we can combine even more than two dictionaries with a single expression. Check its syntax below:

# Merging two dictionaries using unpacking operator
dictMerged = {**dictFirst, **dictSecond}

Alternatively, we can call this approach using the **kwargs in Python. It helps us pass variable-size key-value pairs to a method. It also treats a dictionary as a sequence of key-value pairs.

When used as **kwargs, it decomposes the dictionary into a series of key-value elements. Let’s consider the following dictionary:

sample_dict = { 'emp1' : 22, 'emp2' : 12, 'emp3' : 9, 'emp4' : 14 }

The **kwargs expression would treat the sample_dict as:

**sample_dict => 'emp1' : 22, 'emp2' : 12, 'emp3' : 9, 'emp4' : 14

So, let’s apply **kwargs or unpacking operator to combine the dictionaries. We’ll operate on the two given business units in our problem statement.

"""
Desc:
  Python program to merge two dictionaries using **kwargs
"""
# Define two existing business units as Python dictionaries
unitFirst = { 'Joshua': 10, 'Ryan':5, 'Sally':20, 'Martha':17, 'Aryan':15}
unitSecond = { 'Versha': 11, 'Tomi':7, 'Kelly':12, 'Martha':24, 'Barter':9}

# Merge dictionaries using **kwargs
unitThird = {**unitFirst, **unitSecond}

# Print new business unit
# Also, check if unitSecond values override the unitFirst values or not
print("Unit Third: ", unitThird)
print("Unit First: ", unitFirst)
print("Unit Second: ", unitSecond)

After you execute the above program, it should give you the below output:

Unit Third: {'Sally': 20, 'Ryan': 5, 'Versha': 11, 'Tomi': 7, 'Martha': 24, 'Joshua': 10, 'Aryan': 15, 'Kelly': 12, 'Barter': 9}
Unit First: {'Aryan': 15, 'Martha': 17, 'Joshua': 10, 'Sally': 20, 'Ryan': 5}
Unit Second: {'Barter': 9, 'Martha': 24, 'Kelly': 12, 'Versha': 11, 'Tomi': 7}

Also Read: 5 Ways to Convert Python Dictionary to DataFrame

Combine Two or More Dictionaries

Using the **kwargs method to merge the dictionaries was a very straightforward method.

Let’s also see how it groups three given dictionaries.

"""
Desc:
Python program to merge three dictionaries using **kwargs
"""
# Define two existing business units as Python dictionaries
unitFirst = { 'Joshua': 10, 'Ryan':5, 'Sally':20, 'Martha':17, 'Aryan':15}
unitSecond = { 'Versha': 11, 'Tomi':7, 'Kelly':12, 'Martha':24, 'Barter':9}
unitThird = { 'James': 3, 'Tamur':5, 'Lewis':18, 'Daniel':23}

# Merge three dictionaries using **kwargs
unitFinal = {**unitFirst, **unitSecond, **unitThird}

# Print new business unit
# Also, check if unitSecond values override the unitFirst values or not
print("Unit Final: ", unitFinal)
print("Unit First: ", unitFirst)
print("Unit Second: ", unitSecond)
print("Unit Third: ", unitThird)

You would get the following result upon its execution:

Unit Final: {'Tomi': 7, 'Ryan': 5, 'Tamur': 5, 'Versha': 11, 'James': 3, 'Sally': 20, 'Martha': 24, 'Aryan': 15, 'Daniel': 23, 'Barter': 9, 'Lewis': 18, 'Kelly': 12, 'Joshua': 10}
Unit First: {'Joshua': 10, 'Ryan': 5, 'Martha': 17, 'Sally': 20, 'Aryan': 15}
Unit Second: {'Tomi': 7, 'Barter': 9, 'Martha': 24, 'Versha': 11, 'Kelly': 12}
Unit Third: {'Daniel': 23, 'Tamur': 5, 'James': 3, 'Lewis': 18}

Merge Using Custom Action

While consolidating the data of two or more dictionaries, it is also possible to take some custom action. For example, if a person exists in two units with different work-ex values, then you may like to add up his experience while merging.

Let’s see how to add values for the same keys while combining three dictionaries. Here is a simple example for your help:

"""
Desc:
  Python program to merge dictionaries and add values of same keys
"""
# Define two existing business units as Python dictionaries
unitFirst = { 'Joshua': 10, 'Daniel':5, 'Sally':20, 'Martha':17, 'Aryan':15}
unitSecond = { 'Versha': 11, 'Daniel':7, 'Kelly':12, 'Martha':24, 'Barter':9}

def custom_merge(unit1, unit2):
   # Merge dictionaries and add values of same keys
   out = {**unit1, **unit2}
   for key, value in out.items():
       if key in unit1 and key in unit2:
               out[key] = [value , unit1[key]]
   return out

# Merge dictionaries while adding values of same keys
unitFinal = custom_merge(unitFirst, unitSecond)

# Print new business unit
# Also, check if unitSecond values override the unitFirst values or not
print("Unit Final: ", unitFinal)
print("Unit First: ", unitFirst)
print("Unit Second: ", unitSecond)

The above program provides a custom function that adds values of the same keys in a list. You can cross-check the same by executing the code:

Unit Final: {'Sally': 20, 'Joshua': 10, 'Barter': 9, 'Versha': 11, 'Kelly': 12, 'Daniel': [7, 5], 'Martha': [24, 17], 'Aryan': 15}
Unit First: {'Sally': 20, 'Joshua': 10, 'Daniel': 5, 'Martha': 17, 'Aryan': 15}
Unit Second: {'Barter': 9, 'Kelly': 12, 'Daniel': 7, 'Martha': 24, 'Versha': 11}

There are two common key entries in unit1 and unit2 dictionaries, namely Daniel and Martha. In the output, you can see that the program added their values to a list.

We hope that after wrapping up this tutorial, you should feel comfortable using dictionaries in Python. However, you may practice more with examples to gain confidence.

Also, to learn Python from scratch to depth, read our step-by-step Python tutorial.

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article User Story Template for Agile teams User Story Template in Agile Scrum
Next Article Python Check Integer Number in Range Python Check Integer Number in Range

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x