How to merge two Python dictionaries in a single expression?


Built-in dictionary class has update() method which merges elements of argument dictionary object with calling dictionary object.

>>> a = {1:'a', 2:'b', 3:'c'}
>>> b = {'x':1,'y':2, 'z':3}
>>> a.update(b)
>>> a
{1: 'a', 2: 'b', 3: 'c', 'x': 1, 'y': 2, 'z': 3}

From Python 3.5 onwards, another syntax to merge two dictionaries is available

>>> a = {1:'a', 2:'b', 3:'c'}
>>> b = {'x':1,'y':2, 'z':3}
>>> c = {**a, **b}
>>> c
{1: 'a', 2: 'b', 3: 'c', 'x': 1, 'y': 2, 'z': 3}

Updated on: 30-Jul-2019

102 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements