How to convert a list to a dictionary in Python?


To convert a simple or nested list into a dictionary data object using Python.


In this tutorial we’ll focus on usage of dictionary comprehensions in order to add the content of a Python list iterator into a dictionary.

1. Dict from Python list

Let’s assume that we have the following list:

my_list = [100,200,300,400]

We can easily create a dictionary that has the each item of the list as a key and its square as its paired value.

my_dict = { i : i**2 for i in my_list}
print (my_dict)

We’ll get the following result:

{100: 10000, 200: 40000, 300: 90000, 400: 160000}

2. Convert list to dictionary with index

What if we just want to convert some of our list elements to a dictionary? In this example we’ll enumerate the list and filter out the uneven indexes using the modulo (%) operator.

my_dict2 = { i : i**2 for x,i in enumerate (my_list) if x%2==0 }

Here’s the result:

{100: 10000, 300: 90000}

3. Append list to existing dictionary

Let’s assume we have already a dictionary of students.

my_std_dict = {'Harry': 'male', 'Liam': 'male', 'Jay': 'male'}

We want to append a list of new students, as key,value pairs into the dictionary.

my_new_std_list = ['John', 'male', 'Thelma', 'female', 'Dorothy', 'female']

my_new_std_dict= { i : my_new_std_list[x+1] for x,i in enumerate (my_new_std_list) if x%2==0}



Here’s the output:

{'Harry': 'male', 'Liam': 'male', 'Jay': 'male', 'John': 'male', 'Thelma': 'female', 'Dorothy': 'female'}

4. Two lists into a dictionary in Python using zip

Let’s assume we have two lists as following:

my_list = [100,200,300,400]
my_sec_list = [1,1,0,0]

We would like to join those into a dictionary. This time we’ll use the Python zip function, which will allow us to stitch them together. We’ll then pass the zip object to the dictionary constructor.

dict(zip(my_list, my_sec_list))

The output will be:

{100: 1, 200: 1, 300: 0, 400: 0}