Initialize a Dictionary with keys and values in Python

This tutorial will discuss about unique ways to initialize a dictionary with keys and values in Python.

Table Of Contents

Using Dictionary Comprehension

Suppose you have two lists, one is the list of keys and second is the list of values. Like this,

listOfKeys = ['Atharv', 'Avisha', 'Kartik', 'Justin']
listOfValues = [34, 44, 49, 39]

Now, we want to initialise a dictionary from these two lists.

We can do that, using the Dictionary Comprehension, where we will zip these two list objects into a list of tuples and we will iterate over those tuples using a for loop inside Dictionary Comprehension.

During iteration, we will pick the items from each tuple and add them as a key value pair in the dictionary. All this will be done in a single line using the dictionary comprehension like this,

dictObj = {key: value for key, value in zip(listOfKeys, listOfValues)}

Here we created and initialised dictionary from the two lists.

Let’s see the complete example,

listOfKeys = ['Atharv', 'Avisha', 'Kartik', 'Justin']
listOfValues = [34, 44, 49, 39]

# Initialize a Dictionary from two lists using Dictionary Comprehension
dictObj = {key: value for key, value in zip(listOfKeys, listOfValues)}

print(dictObj)

Output

{'Atharv': 34, 'Avisha': 44, 'Kartik': 49, 'Justin': 39}

Using Dictionary Constructor

There is an another way to initialise the dictionary from two lists. We can zip the two lists together into a zipped object. It will give us a list of tuples and then we can pass this list of tuples into the Dictionary Constructor.

It will give us a Dictionary initialised with this list of tuples, where the values in the first list listOfKeys will be used as a keys, and values from the second list listOfValues will be used as the value field in each of the pair in Dictionary.

Let’s see the complete example,

listOfKeys = ['Atharv', 'Avisha', 'Kartik', 'Justin']
listOfValues = [34, 44, 49, 39]

# Zip lists together to make list of tuples
# and pass to Dictionary Constructor to initialize a Dictionary
dictObj = dict(zip(listOfKeys, listOfValues))

print(dictObj)

Output

{'Atharv': 34, 'Avisha': 44, 'Kartik': 49, 'Justin': 39}

Summary

We learn about two different ways to initialise a dictionary with keys and values in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

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

Scroll to Top