How to unpack a dictionary in python?

A dictionary is a collection of key-value pairs in Python. A dictionary's keys can be used to access its values. However, there are times when you want to extract the key-value pairs and assign them to variables. This is where dictionary unpacking comes in.

To unpack a dictionary in Python, you can use the following syntax:

Output:

John
30
New York

In this example, we have a dictionary my_dict with three key-value pairs. To extract the values of the dictionary and assign them to variables, we use the values() method of the dictionary. The values of the dictionary are represented in a list-like object that this method returns.The values are subsequently assigned to specific variables using the unpacking operator (*). As it matches the order in which the values appear in the values() method, the order in which we assign the variables is crucial.

Be aware that the number of variables and dictionary values must match. If you try to unpack a dictionary with more or fewer variables than values, you'll get a ValueError.

You can also unpack a dictionary into named variables by using the dictionary unpacking syntax:

Output:

John
30
New York

In this example, we access the values of the dictionary using their keys and assign them to named variables. When you need to extract specific values from a dictionary, this method is helpful.

Finally, you can use the ** operator to unpack a dictionary into named arguments when calling a function. For example:

Output:

John is 30 years old and lives in New York

In this example, we define a function print_person that takes three arguments: name, age, and city. After that, we create a dictionary my_dict containing the values of these arguments. We use the dictionary unpacking operator ** to pass the values of the dictionary as named arguments to the function. The result is the same as calling print_person('John', 30, 'New York').






Latest Courses