Convert List To Dictionary In Python

In this short guide, I’ll show you a couple of approaches for how to convert list to dictionary in python. So without further ado let’s get started.

The list in python is the mutable data structure that is used to hold a sequence of any elements. The elements could have the same data type or different data types. It is defined by square brackets [].

The dictionary in python is the builtin data structure that is used to hold unordered key-value pairs. It maps the key to its value. It is defined by curly braces {}.

1. Odd-Even Approach

In this code example, we will convert the list to the dictionary in such a way that all the elements at the odd index will become the key, and elements at even index will become value. Any extra element in the list will be skipped.

Here is the code with proper comments.

#program 1 to Convert List To Dictionary In Python

# list to be converted into dictionary
list1 = ["dog",1,"cat",2,"tiger",3]

dic = {} # initialize an empty dictionary

 # iterate through input list with step size of 2
for i in range(0,len(list1),2):

    # Populate the dictionary
    dic[list1[i]] = list1[i+1]

print(dic)

Here is the output of above code.

Output :

Output of program to Convert List To Dictionary In Python

2. Values As Index

In the following code, we will set the elements of the list as keys and their indices as the value in the dictionary.

#program 2 to Convert List To Dictionary In Python

# input list
x = ["apple","banana","orange"]

dic = {} # initialize an empty dictionary

for i in range(len(x)):
    dic[x[i]] = i

print(dic)

Save and run the above code. you should see the following output.

Output :

{'apple': 0, 'banana': 1, 'orange': 2}

3. Combine Two Lists Into A Dictionary

In the following code snippet, We will combine the two lists into the dictionary where the elements of the first list will act as keys, and elements of the second list will act as the value.

#program 3 to Convert List To Dictionary In Python

x = ["apple","banana","orange"]
y = [100,200,300]

# Check if length of both lists are same
if len(x) == len(y):
    dic = {} # initialize an empty dictionary

    for i in range(len(x)):
        dic[x[i]] = y[i]

    print(dic)

else:
    print("Length of both lists should be same")

Output :

{'apple': 100, 'banana': 200, 'orange': 300}

That’s wrap for this tutorial.

Also read about how to sort a dictionary by value in python

Leave a Reply