Converting a List into a Dictionary in Python

In this tutorial, we will learn how to convert a list into dictionary in Python.

A list is a collection of different data.

In Python, a list shows the following features.

  • It is a mutable sequence.
  • It means the elements in the list can be changed.
  • The elements are accessed by index.

Certainly, it would be a handful to know a bit about Dictionary in Python.

Therefore, a dictionary can be defined as a mutable sequence which has the format of key: value pair.

Moreover, it is an unordered sequence.

Also learn: Convert a Dictionary into a List in Python

Creating a List :

sample_list = [ ]  # empty list

sample_list = [ 1, "rahul" ,2 , "raj" , 3 ,"Bhanu" ,4 , "Surya"]

print (sample_list)
Output :

[1, 'rahul', 2, 'raj', 3, 'Bhanu', 4, 'Surya']

As the list is created, it’s time to convert it into another datatype like Dictionary.

Convert List into a Dictionary in Python

First of all, the above list can be converted into a dictionary by imagining the above list as,

sample_list = [key1, value1, key2, value2, …… so on]

Before converting, certainly, it’s good to see how a dictionary looks like.

Sample Dictionary :

sample_dict = { }

sample_dict = {"a" : 1, "b" : 2 , "c" : 3} # key : value  pair

print(sample_dict)
Output :

{'b': 2, 'a': 1, 'c': 3}

Process 1 :

Combining the above features and the steps, the following can be designed.

sample_list = [ ] # empty list 

sample_list = [ 1, "rahul" ,2 , "raj" , 3 ,"Bhanu" ,4 , "Surya"] 

sample_dict = { } # empty dictionary

len_list = len(sample_list)          # range(a , b , c) <- sequence of a to b-1 with skip of c

for i in range(0,len_list,2):            # imagining key as every integer in the list
    
    key = sample_list [i]           # key element
    
    sample_dict [key] = sample_list [i+1]          # dict [key] = value

print(sample_dict)
Output :

{1: 'rahul', 2: 'raj', 3: 'Bhanu', 4: 'Surya'}

Seems pretty interesting, moreover, there is even another way to convert the list into Dictionary.

Process 2:

The second method is to use the zip ( ) method.

Simply, a zip (a,b) pairs the simultaneous values in a and b [ where a and b are any sequences ].

list_keys = [1 ,2 ,3 ,4 ,5]

list_values = ["ab" , "bc" , "cd" , "gf" , "es"]

sample_dict = { } # empty dictionary

zip_obj = zip(list_keys , list_values) # it creates a tuple where the corresponding values are paired

sample_dict = dict (zip_obj)            # typecasting with dict( seq ) function which converts any sequence to dictionary

print (sample_dict)
Output :

{1: 'ab', 2: 'bc', 3: 'cd', 4: 'gf', 5: 'es'}

Certainly, these are the best and easy ways to convert the list into a dictionary in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *