How To Combine Two Or More Dictionaries In Python with Examples

How To Combine Two Or More Dictionaries In Python with Examples

Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. Key value is provided in the dictionary to make it more optimized.

Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. Key value is provided in the dictionary to make it more optimized.

Have you ever wanted to combine two or more dictionaries in Python? There are various ways in which Dictionaries can be merged by the use of various functions and constructors in Python. In this article, we will discuss few ways of merging dictionaries.

There are mainly two ways that we can use the merge two dictionaries in Python.

  • Merge two or more dictionaries using dict.update()
  • Merge two or more Dictionaries using **kwargs
Here are some examples of how to combine two or more dictionaries in Python

Example 1

Merge two or more dictionaries using dict.update()

Python dictionary update() is an inbuilt method that updates one dictionary with the elements of another dictionary object or from an iterable value of key pair. If a key is not present in the dictionary, it first adds the key to the dictionary.

After that, it combines the value; otherwise, if the key is already present in the dictionary, it just updates the value.

In short, it accepts another dictionary or an Iterable object (collection of key-value pairs) as an argument. Then merges the contents of this passed dictionary or Iterable in the current dictionary.

See the following code.


# app.py

dictA = {'asa': 11, 'emma': 19, 'eric' : 21}

dictB = {'millie': 46, 'finn': 23, 'noah' : 18}

dictA.update(dictB)
 
print('Updated dictionary A :')
print(dictA)

Output


Updated dictionary 1 :
{'asa': 11, 'emma': 19, 'eric': 21, 'millie': 46, 'finn': 23, 'noah': 18}

From the output, you can see that All the items from dictB are added to dictA.

In this example, all the keys are from both the dictionaries are unique.

Let’s take an example in which some of the keys are the same for both the dictionaries and see the output.

# app.py

dictA = {'asa': 11, 'emma': 19, 'eric' : 21}

dictB = {'asa': 46, 'finn': 23, 'eric' : 18}

dictA.update(dictB)
 
print('Updated dictionary A :')
print(dictA)

Output


Updated dictionary A :
{'asa': 46, 'emma': 19, 'eric': 18, 'finn': 23}

So, from the output, you can see that keys that are common in both the dictionaries will contain the values as in dictB. The dictionary we are passing in the update() method as an argument will override the standard key’s values. Therefore ‘asa’ has value 46, and ‘eric‘ has value 18 now.

So, the second dictionary’s value will override the first dictionary value, if the keys are the same in both the dictionaries while doing an update().
The update() method did not create a new dictionary(dictA), it updates the content of the first dictionary(dictA).

Let’s see the second way of how to merge two dictionaries.

Example 2

Merge two or more Dictionaries using **kwargs

The special syntax **kwargs in python is used to pass the keyworded, variable-length argument list. We use the name kwargs with a double star.

The main reason is that the double star allows us to pass through any number of keyword arguments.

  1. A keyword argument is where you provide the name to the variable as you pass it into the function.

  2. You can think of the kwargs as being the dictionary that maps each keyword to a value that we pass alongside it. That is why when we iterate over the kwargs, there doesn’t seem to be any order in which they were printed out.

For example, if we have a dictionary like the following.

dictA = {'asa': 11, 'emma': 19, 'eric' : 21}

When we apply **(double star) to the dictA, it deserializes the contents of the dictionary to a collection of key-value pairs like the following.

**dictA

Is equivalent to this.


'asa': 11, 'emma': 19, 'eric' : 21


Now, see the following code.


# app.py

dictA = {'asa': 11, 'emma': 19, 'eric' : 21}

dictB = {'millie': 46, 'finn': 23, 'noah' : 18}

dictC = {**dictA, **dictB}
 
print('Combined Dictionary C :')
print(dictC)

In the above code, we are creating the third dictionary and assign the deserialized values of two dictionaries to that dictionaries.

So, we are getting combined dictC, which is the third dictionary, and it does not modify the content of the existing two dictionaries.

Output


Combined Dictionary C :
{'asa': 11, 'emma': 19, 'eric': 21, 'millie': 46, 'finn': 23, 'noah': 18}

The **dictA and **dictB expanded the contents of both the dictionaries to a collection of key-value pairs.

Therefore, a new dictionary dictC is created that contains the data from both the dictionaries.

Here also, if the first and second dictionary has the same keys, then the second dictionary’s value will override the first one.

If you change the order like this.

dictC = {**dictB, **dictA}


Then, the content of dictA will override the content of dictB. So, order matters here.

Example 3

Combine three dictionaries in Python

Let’s take three dictionaries and combine all of them and create the fourth dictionary.

# app.py

dictA = {'asa': 11, 'emma': 19, 'eric' : 21}

dictB = {'millie': 46, 'finn': 23, 'noah': 18}

dictC = {'penny': 29, 'sheldon': 36, 'leonard': 2}

dictD = {**dictA, **dictB, **dictC}
 
print('Combined Dictionary D :')
print(dictD)

Output


Combined Dictionary D :
{'asa': 11, 'emma': 19, 'eric': 21, 'millie': 46, 'finn': 23, 'noah': 18, 'penny': 29, 'sheldon': 36, 'leonard': 2}

As you can see Merging two or more dictionaries is an easy task in Python. But to find a better approach is a tough choice for every developer. If you do not have any consequences of modifying the existing dictionary, then you can use the dict.update() method otherwise go for **kwargs approach.

Thanks for reading !

Guide to Python Programming Language

Guide to Python Programming Language

Guide to Python Programming Language

Description
The course will lead you from beginning level to advance in Python Programming Language. You do not need any prior knowledge on Python or any programming language or even programming to join the course and become an expert on the topic.

The course is begin continuously developing by adding lectures regularly.

Please see the Promo and free sample video to get to know more.

Hope you will enjoy it.

Basic knowledge
An Enthusiast Mind
A Computer
Basic Knowledge To Use Computer
Internet Connection
What will you learn
Will Be Expert On Python Programming Language
Build Application On Python Programming Language

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Description
Hello and welcome to brand new series of wiredwiki. In this series i will teach you guys all you need to know about python. This series is designed for beginners but that doesn't means that i will not talk about the advanced stuff as well.

As you may all know by now that my approach of teaching is very simple and straightforward.In this series i will be talking about the all the things you need to know to jump start you python programming skills. This series is designed for noobs who are totally new to programming, so if you don't know any thing about

programming than this is the way to go guys Here is the links to all the videos that i will upload in this whole series.

In this video i will talk about all the basic introduction you need to know about python, which python version to choose, how to install python, how to get around with the interface, how to code your first program. Than we will talk about operators, expressions, numbers, strings, boo leans, lists, dictionaries, tuples and than inputs in python. With

Lots of exercises and more fun stuff, let's get started.

Download free Exercise files.

Dropbox: https://bit.ly/2AW7FYF

Who is the target audience?

First time Python programmers
Students and Teachers
IT pros who want to learn to code
Aspiring data scientists who want to add Python to their tool arsenal
Basic knowledge
Students should be comfortable working in the PC or Mac operating system
What will you learn
know basic programming concept and skill
build 6 text-based application using python
be able to learn other programming languages
be able to build sophisticated system using python in the future

To know more:

Learn Python Programming

Learn Python Programming

Learn Python Programming

Description
Learn Python Programming

Learn Python Programming and increase your python programming skills with Coder Kovid.

Python is the highest growing programming language in this era. You can use Python to do everything like, web development, software development, cognitive development, machine learning, artificial intelligence, etc. You should learn python programming and increase your skills of programming.

In this course of learn python programming you don't need any prior programming knowledge. Every beginner can start with.

Basic knowledge
No prior knowledge needed to learn this course
What will you learn
Write Basic Syntax of Python Programming
Create Basic Real World Application
Program in a fluent manner
Get Familiar in Programming Environment