DEV Community

Cover image for Dictionary Unpacking in Python!
BrendahKiragu
BrendahKiragu

Posted on

Dictionary Unpacking in Python!

Hey there, Python enthusiasts! 💻

Let's talk about the coolest and most underrated tricks in Python that I discovered today: dictionary unpacking (a.k.a. dictionary merging). Whether you’re a beginner or a seasoned coder, this technique can simplify your life when working with dictionaries. Let's dive in!

What Is Dictionary Unpacking?

Imagine you have two dictionaries:

  • Dictionary 1
    first = {"name": "Tim Bradford", "age": 35}

  • Dictionary 2
    second = {"city": "New York", "job": "Hollywood Actor"}

Now, what if you want to combine these dictionaries into one?

Enter dictionary unpacking! Using the ** operator, you can easily merge these:

combined = {**first, **second}
print(combined)

Output:

{'name': 'Tim Bradford', 'age': 35, 'city': 'New York', 'job': 'Hollywood Actor'}
Enter fullscreen mode Exit fullscreen mode

Cool, right? You just created a shiny new dictionary that combines the keys and values of both first and second.

Why Is This Useful?

Merging Dictionaries:
Before Python 3.9, merging dictionaries involved using methods like .update() or creating a custom loop. Dictionary unpacking makes it simple and clean.

Default Values:
Combine your main dictionary with another dictionary containing default values:

defaults = {"theme": "dark", "language": "English"}
user_settings = {"language": "French"}

final_settings = {**defaults, **user_settings}
print(final_settings)

Output:

{'theme': 'dark', 'language': 'French'}
Enter fullscreen mode Exit fullscreen mode

The user’s preference for language takes precedence, thanks to the unpacking order.

Readable Code:
Your colleagues (and future you!) will thank you for this clean and Pythonic approach.

Handling Key Collisions

What happens if both dictionaries have the same key? Let’s see:

a = {"key": "value1"}
b = {"key": "value2"}

result = {**a, **b}
print(result)

Output:

{'key': 'value2'}
Enter fullscreen mode Exit fullscreen mode

The value from the dictionary on the right (b) overrides the one on the left (a). So, order matters when unpacking!

Python 3.9+ Bonus: The | Operator

Starting from Python 3.9, merging dictionaries became even simpler with the | operator:

merged = a | b
print(merged)
Enter fullscreen mode Exit fullscreen mode

This achieves the same result as unpacking but looks even cleaner. For an in-place merge, use |=:

a |= b
print(a)
Enter fullscreen mode Exit fullscreen mode

This updates "a" with the merged dictionary.

A Fun Fact to Wrap Up

Dictionary unpacking isn’t just for merging—it’s also helpful when passing dynamic arguments to functions! If you have:

def greet(name, age, topic, time):
    print(f"Hello, {name}! You are {age} years old. You are here to learn about {topic} at {time}.")

info = {"name": "Marko", "age": 30}
subject = {"topic": "Python", "time": "10:00 AM"}
greet(**info, **subject)

Output:

Hello, Marko! You are 30 years old. You are here to learn about Python at 10:00 AM.
Enter fullscreen mode Exit fullscreen mode

With **info and **subject, you’re unpacking the dictionary to match the function’s parameters. Handy, innit?

Final Thoughts

Dictionary unpacking is a delightful feature that makes Python so elegant and intuitive. It’s clean, readable, and oh-so-powerful.

Got some cool dictionary tricks of your own? Share them in the comments below! And if you’re new to Python, try practicing with this feature—you’ll be amazed at how much smoother your code becomes. Until next time, happy coding! 🚀

Top comments (0)