Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Unpacking Dictionaries with ** | Packing and Unpacking in Python
Functional Programming Concepts in Python

bookUnpacking Dictionaries with **

Swipe to show menu

When working with dictionaries in Python, the ** operator provides a concise and powerful way to unpack their contents. Unpacking with ** allows you to pass dictionary items as named arguments to functions or to merge multiple dictionaries together. This technique is especially useful when you want to write flexible and reusable code that can handle varying sets of named parameters.

The ** operator takes a dictionary and expands its key-value pairs into separate keyword arguments. This is commonly used when calling functions that accept keyword arguments, letting you pass a dictionary directly instead of specifying each argument manually. Another practical use is merging two or more dictionaries into a new one, where all key-value pairs are combined in a single dictionary.

12345
def print_person(name, age): print(f"Name: {name}, Age: {age}") person_info = {"name": "Alice", "age": 28} print_person(**person_info)
copy

This code demonstrates Dictionary Unpacking using the ** operator. When you place ** before a dictionary in a function call, Python "unwraps" the key-value pairs and passes them as individual keyword arguments. In this example, print_person(**person_info) is functionally identical to writing print_person(name="Alice", age=28). For this to work correctly, the dictionary keys must exactly match the parameter names defined in the function signature.

12345
defaults = {"color": "blue", "size": "medium"} overrides = {"size": "large", "style": "bold"} merged = {**defaults, **overrides} print(merged)
copy

Here you can see Dictionary Merging. By placing ** inside a new dictionary literal, Python expands the key-value pairs of both defaults and overrides into a single object.

When keys overlap - like "size" in this example - the dictionary appearing later in the sequence takes precedence. Here, the value "large" from overrides overwrites "medium" from defaults, resulting in a merged dictionary that combines all unique keys while prioritizing the most recent values.

1. What is the result of using ** on a dictionary in a function call?

2. Which method combines two dictionaries using unpacking in Python?

question mark

What is the result of using ** on a dictionary in a function call?

Select the correct answer

question mark

Which method combines two dictionaries using unpacking in Python?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 1. Chapter 3

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Section 1. Chapter 3
some-alt