Updating a dictionary in python

Updating a dictionary in python

Python has this feature built-in:

>>> d = {b: 4}
>>> d.update({a: 2})
>>> d
{a: 2, b: 4}

Or given youre not allowed to use dict.update:

>>> d = dict(d.items() + {a: 2}.items())   # doesnt work in python 3

With python 3.9 you can use an |= update operator:

>>> d = {b: 4}
>>> d |= {a: 2}
>>> d
{a: 2, b: 4}

Updating a dictionary in python

Heres a more elegant solution, compared to Erics 2nd snippet

>>> a = {a : 1, b : 2}
>>> b = {a : 2, c : 3}
>>> c = dict(a, **b)
>>> a
{a: 1, b: 2}
>>> b
{a: 2, c: 3}
>>> c
{a: 2, b: 2, c: 3}

It works both in Python 2 and 3

And of course, the update method

>>> a
{a: 1, b: 2}
>>> b
{a: 2, c: 3}
>>> a.update(b)
>>> a
{a: 2, b: 2, c: 3}

However, be careful with the latter, as might cause you issues in case of misuse like here

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

Leave a Reply

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