AppDividend
Latest Code Tutorials

Python Zip Dictionary: How to Convert List to Dictionary

0

The list and dictionary are among the robust data structures in Python. Converting from each other is the most common task you ever face in Python development. You often find that you have to 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. In Python 3, the zip() method now returns a lazy iterator, which is now the most used approach.

The dict(zip(keys, values)) need the one-time global lookup each for dict and zip. Still, it doesn’t create any needless intermediary data-structures or have to deal with local lookups in function application.

# 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, then 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, then you have to use proper dictionary comprehension.

Dictionary Comprehension

Dictionary comprehension is an elegant and concise way to create dictionaries. 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 a 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

Your email address will not be published.

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