mailwal

[🐍PyTricks]: Merging two dicts in Python 3.5+ with a single expression

Dan at Real Python1 min read
# How to merge two dictionaries
# in Python 3.5+

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

>>> z = {**x, **y}

>>> z
{'c': 4, 'a': 1, 'b': 3}

# In Python 2.x you could
# use this:
>>> z = dict(x, **y)
>>> z
{'a': 1, 'c': 4, 'b': 3}

# In these examples, Python merges dictionary keys
# in the order listed in the expression, overwriting 
# duplicates from left to right.
#
# See: https://www.youtube.com/watch?v=Duexw08KaC8
This email is part of the Python Tricks series where you're getting a new Python trick every few days directly to your inbox. Enjoy!

— Dan Bader (realpython.com)

#720-999 West Broadway, Vancouver BC V5Z 1K5