How to Zip a Dictionary in Python

To zip two dictionaries into a dictionary and two lists into a dictionary in Python, you can use the “zip() function and a dictionary comprehension” or the “dict() constructor.”

Method 1: Using the zip() function and dictionary comprehension

Using the zip() function along with dictionary comprehension is a concise and efficient way to create a dictionary from two lists containing keys and values.

Syntax

dictionary = {key: value for vars in iterable}

Example

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}

Method 2: Using the dict() constructor

Using the dict() constructor and the zip() function is another efficient way to create a dictionary from two lists containing keys and values.

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

print(dictionary)

Output

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

That’s it.

1 thought on “How to Zip a Dictionary in Python”

Leave a Comment

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