How to Unpack Dictionary in Python

How to unpack dictionary in Python

In this article, we will see how to unpack dictionary in Python.

Dictionaries in Python

A dictionary is one of the fundamental data structures of Python. It stores its elements as key-value pairs and has evolved with time. In recent versions of Python, dictionaries use hash functions which make accessing values from keys a fast process and are also known to retain the order of elements.

Python uses the dict class that represents dictionaries as the base for many other objects so many operations are possible with them. We can unpack dictionaries as well.

Unpacking a dictionary means unloading and printing the key-value pairs or loading them in other objects like a tuple or a list. We also unpack a dictionary while sending their values to a function or when we are merging two dictionaries.

For this, we have the unpack operator in Python and loads of various functions that can be utilized.

How to Unpack Dictionary in Python

We will now discuss different ways how to unpack dictionary in Python.

Using the Unpack Operator (**) to Unpack Dictionary in Python

The ** operator is used to pack and unpack dictionary in Python and is useful for sending them to a function. This will be made more clear with an example.

Output:

10 20 30

In the above example, we have a function that accepts three arguments. We pass these three arguments by packing them in a dictionary using the ** operator.

We can use the ** to unpack dictionaries and merge them in a new dict object.

For example,

Output:

{‘k0’: 0, ‘k1’: 10, ‘k2’: 20, ‘k3’: 30}

In the above example, we create a new dictionary by unpacking the contents of the previous dictionary in the new dictionary.

We also have an operator to unpack elements from the list. We can use this operator for dictionaries after converting them to a list of key-value pairs. We will discuss the methods to convert a dictionary to a list of key-value pairs as tuples below and unpack the elements using this operator.

Using the for Loop to Unpack Dictionary in Python

Dictionaries are iterable in Python. We can use the for loop to iterate by a dictionary and print its contents.

While iterating through a dictionary, we use its keys. We will then use the keys to access the value at every iteration and display them both.

See the following example.

Output:

Key k1 Value 10
Key k2 Value 20
Key k3 Value 30

In every iteration, we use the k variable to access the value at the given iteration and display them both.

We can also append them to a list of tuples. For this, we will create an empty list and append the key-value pairs as a tuple in every iteration.

For example,

Output:

[(‘k1’, 10), (‘k2’, 20), (‘k3’, 30)]

In the above example, we first created an empty list lst and then went on to append the key-value pairs as a tuple using the append() function.

After creating the list, we can unpack the elements using the unpack operator(*) operator discussed previously.

See the code below.

Output:

(‘k1’, 10) (‘k2’, 20) (‘k3’, 30)

Using the iteritems() Function to Unpack Dictionary in Python

The iteritems() function was available in Python 2 and it would return the key-value pairs of the dictionary in a view object.

We can use it to unpack dictionary in Python.

For example,

Output:

[(‘k3’, 30), (‘k2’, 20), (‘k1’, 10)]

This function was replaced by the items() function in Python 3.

Using the items() Function to Unpack Dictionary in Python

The items() function replaced the iteritems() function in Python 3 and returns a better view object of the dictionary backed by the dict class. This function returns an object of type dict_items.

We can use the unpack operator (*) for lists with this object.

For example,

Output:

(‘k1’, 10) (‘k2’, 20) (‘k3’, 30)

In the above example, we can observe the type of object returned by the items() function is similar to a list but is backed by the dict class.

This function is also available in Python 2. However, in Python 2, this method directly returns a list of the elements of the dictionary and not a view-object. Any changes made in the dictionary after the items() function call will not be observed in the returned list in Python 2.

Using the keys and values Functions to Unpack Dictionary in Python

The keys() and values() function of the dict class return a view-like object of the keys and values of a dictionary respectively.

We can use these functions with the zip() method to unpack dictionary in Python.

See the code below.

Output:

(‘k1’, 10) (‘k2’, 20) (‘k3’, 30)

In the above example,

  • The zip() method combines the corresponding elements at each position in the view objects.
  • This object is converted to a list using the list() function.
  • Elements are unpacked from this list using the unpack operator.

Conclusion

To conclude, in this article we discussed dictionaries and how to unpack dictionary in Python. We started by discussing dictionaries and unpack operations in Python. We can use the unpack operators with dictionaries in Python. The ** is directly used for packing and sending a dictionary as a function argument. We can also use this to unpack and merge dictionaries. We also have the unpack operator (*) operator that can unpack elements from lists or tuples. To use this, we convert the dictionary to a list of tuples and unpack the elements from this list. Several functions can be used to convert a dictionary to a list and then unpack them.

That’s all about how to unpack dictionary in Python.


import_contacts

You may also like:

Related Posts

  • Make requirements.txt in Python
    03 May

    Make requirements.txt in python

    Table of ContentsWhat is the requirements.txt file in Python?Ways to make requirements.txt file in PythonUsing the pip to make requirements.txt in PythonUsing the conda command to make requirements.txt file in PythonUsing the pipreqs package to make requirements.txt file in PythonConclusion What is the requirements.txt file in Python? Every package is also updated regularly and features […]

  • Create an array of 1 to 10 in Python
    03 May

    Create an Array of 1 to 10 in Python

    Table of ContentsIntroductionHow to create an array of 1 to 10 in Python?Using the range() function to create an array of 1 to 10 in Python.Using list comprehension along with the range() function to create an array of 1 to 10 in Python.Using a user-defined function to create an array of 1 to 10 in […]

  • Remove Urls from String in Python
    03 May

    Remove Urls from Text in Python

    Table of ContentsIntroductionWays to remove URLs from Text in PythonUsing the re.sub() function to remove URLs from Text in PythonUsing the re.findall() function to remove URLs from Text in PythonUsing the re.search() function to remove URLs from Text in PythonUsing the urllib.urlparse class to remove URLs from Text in PythonConclusion In this post, we will […]

  • Create a list from 1 to 100 in Python
    03 May

    Create a List from 1 to 100 in Python

    Table of ContentsWays to create a list from 1 to 100 in PythonUsing the range() function to create a list from 1 to 100 in PythonUsing the numpy.arange() function to create a list from 1 to 100 in PythonUsing the for loop with range() to create a list from 1 to 100 in PythonConclusion In […]

  • Return vs Print in Python
    16 April

    Return vs Print in Python

    Table of ContentsReturn vs Print in PythonConclusion Return vs Print in Python In Python, we work with a wide range of functions that make our code simple. We can also create functions using the def keyword. A function can be defined as per our requirement and can display something or return a value. This is […]

  • Floor division in Python
    10 April

    Floor division in Python

    Table of ContentsWhat is Floor Division in Python?How to implement floor division in Python?Using the // operator to implement floor division in Python.Using the // operator to implement floor division on negative integers in Python.Using the // operator to implement floor division on floating-point numbers in Python.Using the // operator to implement floor division with […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.