• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

8 Different Ways to Merge Two Dictionaries in Python

August 4, 2020 by javainterviewpoint Leave a Comment

In this article, we will discuss the different ways to merge two dictionaries in Python. Python dictionary is an unordered collection of items. We will be using the below approaches to merge two dictionaries

  1. update() method
  2. copy() and update() method
  3. ** operator
  4. dict() constructor
  5. dict() with **kwargs
  6. Concatenation in dict()
  7. collections – ChainMap
  8. itertools – chain

Merge Two Dictionaries in Python

Merge Two Dictionaries in Python

1. update() method

In this approach, we will be calling update() method, and this method updates the current dictionary with the content of the dictionary or any iterable of key/value pairs that are passed to it.

If we have two dictionaries like below

>>> d1 = {'Cricket':'Sachin', 'Football':'Zindane'}
>>> d2 = {'Tennis' : 'Roger', 'Basketball' : 'Jordan'}

We can simply merge the two dictionaries bypassing d2 to the update() method

>>> d1.update(d2)

Now, d1 will have its original key/value pairs along with the content of d2.

>>> print(d1)
{'Cricket': 'Sachin', 'Football': 'Zindane', 'Tennis': 'Roger', 'Basketball': 'Jordan'}

The important point to be noted here is we did not get a new dictionary. Instead, the key/value pairs of the dictionary d2 got appended with dictionary d1.

What if we needed a new dictionary? The solution is straightforward. We need to call the update() function on the newly created dictionary twice, like below.

>>> d3 = {}
>>> d3.update(d1)
>>> d3.update(d2)
>>> d3
{'Cricket': 'Sachin', 'Football': 'Zindane', 'Tennis': 'Roger', 'Basketball': 'Jordan'}

What if we have the same key in both dictionaries?

>>> d1 = {'Cricket':'Sachin', 'Football':'Zindane'}
>>> d2 = {'Tennis' : 'Roger', 'Cricket' : 'Lara'}

Let’s now try to merge both the dictionaries

>>> d1.update(d2)
>>> d1
{'Cricket': 'Lara', 'Football': 'Zindane', 'Tennis': 'Roger'}

As we have the same keys (Cricket) in both the dictionaries, while performing the update operation, the latest value overrides the old values.

Now when we print the d1 dictionary, we will be able to ‘Lara’ as the value instead of ‘Sachin’ for the key ‘Cricket.‘

2. copy() and update() method

In this approach, we will create a copy of the dictionary d1 using copy() function and assign it to a dictionary d3 and update the new dictionary d3 with the dictionary with d2 using update() function.

>>> d1 = {'Cricket':'Sachin', 'Football':'Zindane'}
>>> d2 = {'Tennis' : 'Roger', 'Basketball' : 'Jordan'}
>>> d3 = d1.copy()
>>> d3
{'Cricket': 'Sachin', 'Football': 'Zindane'}
>>> d3.update(d2)
>>> d3
{'Cricket': 'Sachin', 'Football': 'Zindane', 'Tennis': 'Roger', 'Basketball': 'Jordan'}

This approach is slightly different from the previous approach, where we started with copying d1 to d3, followed by updating d3 with d2.

3. ** operator – Unpacking Operator

It is the most commonly used method to merge two dictionaries [Works with Python 3.5 or greater].

We all know that ** operator unpacks a dictionary, all we need to do is just unpack the dictionaries and merge them into a new dictionary.

>>> d1 = {'Cricket':'Sachin', 'Football':'Zindane'}
>>> d2 = {'Tennis' : 'Roger', 'Basketball' : 'Jordan'}
>>> d3 = {**d1, **d2}
>>> d3
{'Cricket': 'Sachin', 'Football': 'Zindane', 'Tennis': 'Roger', 'Basketball': 'Jordan'}

We just unpacked both the dictionaries d1 and d2 using ** operator [Python kwargs] and merge them into a new dictionary d3.

In this approach, we can merge any number of dictionaries, say, for example, let’s merge the dictionaries d1, d2, d3 into a new dictionary d4.

>>> d1 = {'Cricket':'Sachin', 'Football':'Zindane'}
>>> d2 = {'Tennis' : 'Roger', 'Basketball' : 'Jordan'}
>>> d3 = {'Moto' : 'Rossi', 'Shuttle' : 'Sindhu'}
>>> d4 = {**d1, **d2, **d3}
>>> d4
{'Cricket': 'Sachin', 'Football': 'Zindane', 'Tennis': 'Roger', 'Basketball': 'Jordan', 'Moto': 'Rossi', 'Shuttle': 'Sindhu'}

Now dictionary d4 will have all the contents of dictionaries d1, d2, and d3.

4. dict() constructor

This approach is almost similar to the second approach, where we used a copy() and update() function, in this approach we will use the dict() constructor and followed by update() function call.

>>> d1 = {'Cricket':'Sachin', 'Football':'Zindane'}
>>> d2 = {'Tennis' : 'Roger', 'Basketball' : 'Jordan'}
>>> d3 = dict(d1)
>>> d3.update(d2)
>>> d3
{'Cricket': 'Sachin', 'Football': 'Zindane', 'Tennis': 'Roger', 'Basketball': 'Jordan'}

The dict() constructor creates a dictionary in Python, it can take **kwargs as a parameter, and since we have passed d1 as the parameter, it unpacks and adds the content to dictionary d3.

Now to merge the content of d2 with d3, by calling update() function and pass dictionary d2 to it.

5. dict() with **kwargs

This approach is kind of a shortcut to the above approach; in this approach, we will use a different dict() constructor, which can take a mapping and **kwargs.

>>> d1 = {'Cricket':'Sachin', 'Football':'Zindane'}
>>> d2 = {'Tennis' : 'Roger', 'Basketball' : 'Jordan'}
>>> d3 = dict(d1, **d2)
>>> d3
{'Cricket': 'Sachin', 'Football': 'Zindane', 'Tennis': 'Roger', 'Basketball': 'Jordan'}

We just need to pass dictionary d1 and unpacked dictionary d2 using **kwargs to the dict() constructor. This creates a new dictionary d3 with the content of both d1 and d2.

6. Concatenation in dict()

In this approach, we will create a list of dictionary items and concatenate both the list and pass it to the dict() constructor.

>>> d1 = {'Cricket':'Sachin', 'Football':'Zindane'}
>>> d2 = {'Tennis' : 'Roger', 'Basketball' : 'Jordan'}
>>> d3 = (list(d1.items()) + list(d2.items()))
>>> d3
[('Cricket', 'Sachin'), ('Football', 'Zindane'), ('Tennis', 'Roger'), ('Basketball', 'Jordan')]

The items() function returns the individual items present in the particular dictionary, For example

>>> d1.items()
dict_items([('Cricket', 'Sachin'), ('Football', 'Zindane')])

List of items will create a list out of the items present

>>> list(d1.items())
[('Cricket', 'Sachin'), ('Football', 'Zindane')]

Now, all we need to do is just concatenate both the list and pass it to the dict() constructor.

Note: If you are using Python 2, then we can directly pass the dictionary items to the dict() constructor, an additional list is not required.

d3 = (d1.items() + d2.items()) # Works only in Python 2

7. collections – ChainMap

A ChainMap can group multiple dictionaries and return a single view out of it. This is often faster than creating a new dictionary and running multiple update() calls.

>>> d1 = {'Cricket':'Sachin', 'Football':'Zindane'}
>>> d2 = {'Tennis' : 'Roger', 'Basketball' : 'Jordan'}
>>> from collections import ChainMap
>>> d3 = dict(ChainMap(d1, d2))
>>> d3
{'Tennis': 'Roger', 'Basketball': 'Jordan', 'Cricket': 'Sachin', 'Football': 'Zindane'}

We need to import the ChainMap from the collections. ChainMap(d1, d2) returns the ChainMap instance, which is a dictionary-like mapping, we need to pass it to the dict() constructor to create a new dictionary.

8. itertools – chain

The chain() function takes up the *args parameter (*iterables). This function returns the element from each iterable so that it can be used to create a single sequence.

>>> d1 = {'Cricket':'Sachin', 'Football':'Zindane'}
>>> d2 = {'Tennis' : 'Roger', 'Basketball' : 'Jordan'}
>>> from itertools import chain
>>> d3 = dict(chain(d1.items(), d2.items()))
>>> d3
{'Cricket': 'Sachin', 'Football': 'Zindane', 'Tennis': 'Roger', 'Basketball': 'Jordan'}

We need to import the chain from the itertools, this returns the elements of both the dictionary d1 and d2. The returned elements can be passed to the dict() constructor to create a new dictionary.

Do let me know if you come across any new way to merge two Dictionaries in Python. Happy Learning!!

Filed Under: Python Tagged With: ** operator, **kwargs, chain, ChainMap, copy(), dict() constructor, Dictionaries in Python, itertools, Merge Two Dictionaries, update()

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·