How to Create a Python Dictionary in One Line?

Python

Interview Question

Suppose we have two Lists.

We need to Create a Dictionary from these two Lists, but in ONE LINE only.

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

Two Lists

A  Dictionary stores the items as key value pairs. So, new Dictionary should be like this,

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

Python Dictionary

Zip Both the lists together using zip() method. It will return a sequence of tuples. 

Each ith element in tuple will have ith item from each list.

listOfTuples = zip(keys, values)

Zip the Lists

Pass the list of tuples to dictionary constructor to create a Dictionary.

obj = dict(zip(keys, values))

Dictionary will be created from two lists in one line.

Dictionary Constructor

Another WAY

Dictionary Comprehension

There is another way to create a Dictionary from two lists, in One line i.e. using Dictionary Comprehension

Iterate over 0 to N in a Dictionary comprehension. Where, N is the size of lists. During iteration, for each index i, fetch key & value from ith position in lists and add in Dictionary,

students = \           {keys[i]: values[i] \            for i in range(len(keys))}

Dictionary will be created from two lists in one line.

Dictionary Comprehension