How to merge two Python dictionaries in a single expression?

PythonServer Side ProgrammingProgramming

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}
raja
Published on 29-Dec-2017 10:33:37
Advertisements