In this article we will discuss different ways to convert a single or multiple lists to dictionary in Python.

Following conversions from list to dictionary will be covered here,

  • Convert a List to Dictionary with same values
  • Convert List items as keys in dictionary with enumerated value
  • Convert two lists to dictionary
  • Convert a list of tuples to dictionary

Convert a List to Dictionary with same values

Suppose we have a list of strings i.e.

Now we want to create a dictionary with all elements in this list as keys. For each key value will be same i.e. 5. Let’s see how to do that i.e.

Using dictionary comprehension

Dictionary contents will be,

Using dict.fromKeys()

dict.fromKeys() accepts a list and default value. It returns a dictionary with items in list as keys. All dictionary items will have same value, that was passed in fromkeys().

If no default value was passed in fromKeys() then default value for keys in dictionary will be None.

Convert List items as keys in dictionary with enumerated value

Suppose we have a list of strings i.e.

Let’s create a dictionary from this list with list elements as keys and values as integers from 0 to n-1 (n is size of list) i.e.

Dictionary contents will be,

Convert two lists to a dictionary

Suppose we have two lists i.e.

Let’s create a dictionary with elements of listOfStr as keys and elements of listOfInt as values using zip() i.e

Zip() accepts a number of iterable objects and returns a list of tuples. Each entry in tuple contains an element from each iterable object.
We have passed two lists objects in zip() , so it will return a list of tuples, where each tuple contains an entry from both the lists. Then we created a dictionary object from this list of tuples.

Dictionary contents are,

  • If length of keys list is less than list of values then remaining elements in value list will be skipped.

Convert a list of tuples to dictionary

Suppose we have a list of tuples with two columns in each entry i.e.

We can directly pass this list of tuples to dictionary constructor i.e

Entries in first column will become the key and entries in second column will the values in the new dictionary. Contents of dictionary will be,

Complete example is as follows,

Output

 

Click Here to Subscribe for more Articles / Tutorials like this.