How to Unpack Dictionary in Python: Simple Guide
** operator inside function calls or when creating new dictionaries. This spreads the key-value pairs into the new context, making it easy to merge or pass dictionary contents.Syntax
The basic syntax to unpack a dictionary uses the ** operator before the dictionary name. It can be used in function calls or when creating new dictionaries.
func(**dict): Passes all key-value pairs as named arguments to a function.{**dict1, **dict2}: Creates a new dictionary by merging others.
def greet(name, age): print(f"Hello {name}, you are {age} years old.") person = {"name": "Alice", "age": 30} greet(**person) # Merging dictionaries info1 = {"city": "Paris"} info2 = {"country": "France"} full_info = {**info1, **info2} print(full_info)
Example
This example shows how to unpack a dictionary to pass its contents as arguments to a function and how to merge two dictionaries into one.
def describe_pet(name, species): print(f"I have a {species} named {name}.") pet_info = {"name": "Buddy", "species": "dog"} describe_pet(**pet_info) # Merging dictionaries stats1 = {"height": 180, "weight": 75} stats2 = {"age": 25, "eye_color": "blue"} combined_stats = {**stats1, **stats2} print(combined_stats)
Common Pitfalls
One common mistake is trying to unpack a dictionary without using the ** operator, which causes errors. Another is unpacking dictionaries with overlapping keys when merging, which overwrites earlier values silently.
Also, unpacking dictionaries into functions requires the keys to match the function's parameter names exactly.
def show_info(name, age): print(f"Name: {name}, Age: {age}") info = {"name": "Bob", "age": 40} # Wrong: missing ** causes TypeError # show_info(info) # This will raise an error # Correct: show_info(**info) # Overlapping keys example first = {"a": 1, "b": 2} second = {"b": 3, "c": 4} merged = {**first, **second} print(merged) # 'b' key value is 3, second dict overwrites first
Quick Reference
Use **dict to unpack dictionaries in these common cases:
- Function calls:
func(**my_dict) - Dictionary merging:
new_dict = {**dict1, **dict2} - Creating copies:
copy = {**original}
Remember keys must match function parameters and overlapping keys overwrite in merges.