Create Python Dictionary in One Line

This tutorial will discuss about unique ways to create a Dictionary in one line in Python.

Table Of Contents

Using Dictionary Comprehension

Suppose we have a list of keys and list of values,

keys = ['Ritika', 'Smriti', 'Mathew', 'Justin']
values = [34, 41, 42, 38]

We want to populate a dictionary with these lists, but in a single line. We can do that using Dictionary Comprehension.

First, zip the lists of keys values using the zip() method, to get a sequence of tuples. Then iterate over this sequence of tuples using a for loop inside a dictionary comprehension and for each tuple initialised a key value pair in the dictionary. All these can be done in a single line using the dictionary comprehension like this,

dictObj = {key: value for key, value in zip(keys, values)}

Here we created a dictionary from two lists in a single line.

Let’s see the complete example,

# A List of Keys
keys = ['Ritika', 'Smriti', 'Mathew', 'Justin']

# A List of Values
values = [34, 41, 42, 38]

# Create a dictionary using Dictionary Comprehension
dictObj = {key: value for key, value in zip(keys, values)}

# Print the dictionary
print(dictObj)

Output

{'Ritika': 34, 'Smriti': 41, 'Mathew': 42, 'Justin': 38}

Using Dictionary Constructor

Suppose you have a list of tuples. Where, each table contains two elements, first one is the key and the second one is the value i.e.

listOfTuples = [('Ritika', 34),
                ('Smriti', 41),
                ('Mathew', 42),
                ('Justin', 38)]

Now we want to create a dictionary from the list of tuples in a single line. For that we can use the dictionary constructor. We can pass the list of tuples in the dictionary constructor and it will return a dictionary initialised with the tuples in the list. First value of each tuple will be used as key and the second value will be used as values, while initializing the dictionary. Like this,

dictObj = dict(listOfTuples)

Here we created a dictionary from list of tuples in one line.

Let’s see the complete example,

# A List of tuples
listOfTuples = [('Ritika', 34),
                ('Smriti', 41),
                ('Mathew', 42),
                ('Justin', 38)]

# Create a dictionary using dict() Constructor
dictObj = dict(listOfTuples)

# Print the dictionary
print(dictObj)

Output

{'Ritika': 34, 'Smriti': 41, 'Mathew': 42, 'Justin': 38}

Summary

We learned about two different ways to create a Dictionary in One Line 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