Sitemap
Amit Patil Algur

Amit Patil Algur

ಕನ್ನಡ ಓದುಗ/Kannada Reader | ಬರೆಯಲು ಪ್ರಯತ್ನಿಸುತ್ತಿರುವವ/Learning to write | My Blog: https://amitdp.wordpress.com/ | Software Professional

Dictionary unpacking in Python

2 min readMay 21, 2024

--

Press enter or click to view image in full size

Dictionary unpacking using the ** syntax in Python allows you to spread the key-value pairs of one dictionary into another dictionary. This is similar to the * operator, which is used for unpacking iterables like lists or tuples.

How Dictionary Unpacking Works

When you use the ** operator with dictionaries, it effectively takes all key-value pairs from the specified dictionary and inserts them into a new dictionary. This is particularly useful for merging dictionaries or for passing dictionary items as keyword arguments to a function.

Examples of Dictionary Unpacking

Merging Dictionaries

You can merge multiple dictionaries into a single dictionary using the ** syntax. Let's consider three dictionaries:

x = {‘a’: 1, ‘b’: 2}
y = {‘b’: 3, ‘c’: 4}
a = {‘a’: 1, ‘b’: 5}

To merge these dictionaries, you can do:

z = {**x, **y, **a}

This results in:

z = {‘a’: 1, ‘b’: 5, ‘c’: 4}

In this merged dictionary, the values for duplicate keys are overwritten in the order of unpacking, with later values taking precedence.

Passing Keyword Arguments

You can also use dictionary unpacking to pass keyword arguments to a function. For example:

def my_function(a, b, c): print(a, b, c) args = {‘a’: 1, ‘b’: 2, ‘c’: 3} my_function(**args)

This will output:

1 2 3

Get Amit Patil Algur’s stories in your inbox

Join Medium for free to get updates from this writer.

Here, **args unpacks the dictionary args into keyword arguments for my_function.

Detailed Breakdown

  • Unpacking a Single Dictionary:

x = {‘a’: 1, ‘b’: 2} z = {**x}

This simply creates a new dictionary z that is a copy of x.

  • Unpacking Multiple Dictionaries:

y = {‘b’: 3, ‘c’: 4}

z = {**x, **y}

This merges x and y into z. If there are duplicate keys, the values from y will overwrite those from x.

Handling Conflicts

When multiple dictionaries have the same keys, the value from the dictionary that is unpacked last will be used. For example:

d1 = {‘key1’: ‘value1’, ‘key2’: ‘value2’}

d2 = {‘key2’: ‘new_value2’, ‘key3’: ‘value3’}

d3 = {‘key1’: ‘new_value1’, ‘key3’: ‘new_value3’}

result = {**d1, **d2, **d3}

The resulting result dictionary will be:

{‘key1’: ‘new_value1’, ‘key2’: ‘new_value2’, ‘key3’: ‘new_value3’}

In this case, d2 overwrites d1, and d3 overwrites both d1 and d2 for overlapping keys.

#dictionaryunpacking #python #dictionary

Connect on LinkedIn: https://www.linkedin.com/in/amitdp28/

--

--

Amit Patil Algur
Amit Patil Algur

Written by Amit Patil Algur

ಕನ್ನಡ ಓದುಗ/Kannada Reader | ಬರೆಯಲು ಪ್ರಯತ್ನಿಸುತ್ತಿರುವವ/Learning to write | My Blog: https://amitdp.wordpress.com/ | Software Professional