Python Zip Dictionary: How to Convert List to Dictionary

0
1273
Python Zip Dictionary - How to Convert List to Dictionary using zip()

The list and dictionary are among the robust data structures in Python. Converting from each other is the most common task you have ever faced in Python development. For example, you often create a dictionary from two different but closely related sequences. An easy way to approach this is to use the dict() and zip() methods together.

Python zip dictionary

To create a dictionary from two sequences, use the dict() and zip() method. The dict(zip(keys, values)) needs the one-time global lookup each for dict and zip. Still, it doesn’t create any needless intermediary data structures or deal with local lookups in function applications.

In Python 3, the zip() method now returns a lazy iterator, the most used approach.

# app.py

stocks = ['reliance', 'infosys', 'tcs']
prices = [2175, 1127, 2750]
dictionary = dict(zip(stocks, prices))
print(dictionary)

Output

{'reliance': 2175, 'infosys': 1127, 'tcs': 2750}

In this example, we have defined two lists that we need to convert into a dictionary. The first list of items will be keys for the dictionary, and the second list of items will be the dictionary.

The zip(fields, values) method returns an iterator that generates two-items tuples. If you call dict() on that iterator, you can create the dictionary you need. The items of the first list become the dictionary’s keys, and the elements second list represent the values in the dictionary.

One important thing to note that dictionary = {zip(keys, values)} will not work. You have to declare as dict(zip()) explicitly. If you make it work, you have to use proper dictionary comprehension.

Dictionary Comprehension

Dictionary comprehension is an elegant and concise way to create dictionaries. For example, we can use the above example to create a dictionary from two lists.

The minimal syntax for dictionary comprehension is the following.

dictionary = {key: value for vars in iterable}

See the following code example of dictionary comprehension.

# app.py

stocks = ['reliance', 'infosys', 'tcs']
prices = [2175, 1127, 2750]

new_dict = {stocks: prices for stocks, prices in zip(stocks, prices)}
print(new_dict)

Output

{'reliance': 2175, 'infosys': 1127, 'tcs': 2750}

That is it for the Python zip dictionary example.

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.