Skip to content
  • YouTube
  • FaceBook
  • Twitter
  • Instagram

Data Analytics Ireland

Data Analytics and Video Tutorials

  • Home
  • Contact
  • About Us
    • Latest
    • Write for us
    • Learn more information about our website
  • Useful Links
  • Glossary
  • All Categories
  • Faq
  • Livestream
  • Toggle search form
  • YouTube channel lists – Python working with files Python working with files
  • How To Fix TypeError: unhashable type ‘slice’ python dictionaries
  • how to create an instance of a class class
  • What are measures in Tableau? data visualisation
  • Import a CSV file with an SQL query CSV
  • Tkinter GUI tutorial python – how to clean excel data Python
  • What are the reserved keywords in Python Definition
  • How can I filter my data in Tableau? data visualisation

how do I merge two dictionaries in Python?

Posted on January 27, 2021April 11, 2021 By admin No Comments on how do I merge two dictionaries in Python?

Python dictionaries which are used in data analytics frequently and by their nature are enclosed in {} and have key:value pairs, so the data in them can be retrieved easily.

There maybe a scenario where you need to merge two dictionaries, but how would you acheive this?

The good thing is that Python dictionaries are unordered and mutable, meaning that what makes them up can be changed.

Lets start off by creating two dictionaries

dict1 = {"A":"1", "B":"2", "C":"3"}
dict2 = {"D":"4", "E":"5", "F":"6"}
print("dictionary 1 is:", dict1)
print("dictionary 2 is:", dict2)
print(type(dict1))
print(type(dict2))

Its output is as follows:
dictionary 1 is: {'A': '1', 'B': '2', 'C': '3'}
dictionary 2 is: {'D': '4', 'E': '5', 'F': '6'}
<class 'dict'>
<class 'dict'>

So the objective is to get these two dictionaries into one, how is this achieved?

Approach 1 – Use PEP 448

This approach uses PEP 448 which allows * iterable unpacking operator and ** dictionary unpacking operators to be implemented.

As can be seen below , it is a quick and efficient way to quickly merge, without impacting the two dictionaries structure.

dict3 = {**dict1, **dict2}
print(dict3)
print(type(3))

With output:
{'A': '1', 'B': '2', 'C': '3', 'D': '4', 'E': '5', 'F': '6'}
<class 'int'>

Approach 2 – Update when some values not required.

You maybe faced with a situation where you only want certain values from the second dictionary.

In the below there are common keys to both dictionares, namely “A” and “B”.

What the update is doing is it keeps all the values of dictionary 1, and adds in any key value pair that is not A or B.

This scenario could be encountered where dict1 is the master dictionary and always correct, and just needs new values added that do not exist already.

dict1 = {"A":"1", "B":"2", "C":"3"}
dict2 = {"A":"2", "E":"5", "B":"6"}
dict2.update((dict1))
print(dict2)
print(type(dict2))

Resulting in:
{'A': '1', 'E': '5', 'B': '2', 'C': '3'}
<class 'dict'>

Approach 3 – Iterating over the dictionaries

In this scenario, there are a few things going on, that should be explained.

dict1.copy ===> This is done so that you have the original, as it maybe updated if there where duplicate keys.

The loop then just goes through dict2 key value pairs, and adds the key value pairs to dict3, which was originally dict1.

dict1 = {"A":"1", "B":"2", "C":"3"}
dict2 = {"D":"4", "E":"5", "F":"6"}

dict3 = dict1.copy()

for key,value in dict2.items():
    dict3[key] = value
print(dict3)

Which gives you:
{'A': '1', 'B': '2', 'C': '3', 'D': '4', 'E': '5', 'F': '6'}
<class 'dict'>

Summing it all up

In conclusion, depending on what way you would like to approach, we have outlined options.

Probably the most important thing that came out of this, is that dictionaries can be changed, as a result when applying some of the

techniques above, before proceeding be sure to check if you want to keep the original values.

Python, python dictionaries Tags:iterate over dictionaries, iterating, key value pairs, merge dictionaries, merge python dictionaries, pep 448

Post navigation

Previous Post: ValueError: invalid literal for int() with base 10
Next Post: how to remove spaces from a string

Related Posts

  • How To Validate Cell Values In Excel Python
  • How to check if a file is empty Python
  • ValueError: Columns must be same length as key exception handling
  • How to sort a Python Dictionary Python
  • Tkinter python tutorial Python
  • How To Create An Empty Dictionary In Python python dictionaries

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Select your language!

  • हिंदी
  • Español
  • Português
  • Français
  • Italiano
  • Python Tutorial: Add a column to a data frame Python Dataframe
  • Python Tutorial: How to validate data using tuples Python Tuples
  • Tkinter python tutorial Python
  • YouTube channel lists – Python DataFrames Python Dataframe
  • TypeError: ‘float’ object is not callable Python
  • What is data profiling and its benefits? data profiling
  • Python tutorial: How to create a graphical user interface in Tkinter Python
  • TypeError: ‘str’ object is not callable Python Functions

Copyright © 2023 Data Analytics Ireland.

Powered by PressBook Premium theme

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Cookie settingsACCEPT
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Non-necessary
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
SAVE & ACCEPT