Improve Your Python With:

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days:

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge
Python Tricks

Q: What’s a Python Trick?

A short Python code snippet meant as a teaching tool. A Python Trick either teaches an aspect of Python with a simple illustration, or serves as a motivating example to dig deeper and develop an intuitive understanding.

Here are a few examples of the kinds of tricks you’ll receive:

Language: Python
# 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}
Language: Python
# Why Python Is Great:
# Function argument unpacking

def myfunc(x, y, z):
    print(x, y, z)

tuple_vec = (1, 0, 1)
dict_vec = {'x': 1, 'y': 0, 'z': 1}

>>> myfunc(*tuple_vec)
1, 0, 1

>>> myfunc(**dict_vec)
1, 0, 1
Language: Python
# The lambda keyword in Python provides a
# shortcut for declaring small and
# anonymous functions:

>>> add = lambda x, y: x + y
>>> add(5, 3)
8

# You could declare the same add()
# function with the def keyword:

>>> def add(x, y):
...     return x