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

Unpacking Dictionaries with **

Scorri per mostrare il 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)

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)

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?

Seleziona la risposta corretta

question mark

Which method combines two dictionaries using unpacking in Python?

Seleziona la risposta corretta

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 1. Capitolo 4

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Sezione 1. Capitolo 4
some-alt