How to convert list to dictionary in Python?

PythonServer Side ProgrammingProgramming

The list is a linear data structure containing data elements.

Example

1,2,3,4,5,6

Dictionary is a data structure consisting of key: value pairs. Keys are unique and each key has some value associated with it.

Example

1:2, 3:4, 5:6

Given a list, convert this list into the dictionary, such that the odd position elements are the keys and the even position elements are the values as depicted in the above example.

Method 1 − Iterating over the list

Example

 Live Demo

def convert(l):
   dic={}
   for i in range(0,len(l),2):
      dic[l[i]]=l[i+1]

   return dic

ar=[1,'Delhi',2,'Kolkata',3,'Bangalore',4,'Noida']
print(convert(ar))

Output

{1: 'Delhi', 2: 'Kolkata', 3: 'Bangalore', 4: 'Noida'}

Method 2 − Using zip()

Initialize an iterator to the variable i. After that zip together the key and values and typecast into a dictionary using dict().

Example

 Live Demo

def convert(l):
   i=iter(l)
   dic=dict(zip(i,i))
   return dic

ar=[1,'Delhi',2,'Kolkata',3,'Bangalore',4,'Noida']
print(convert(ar))

Output

{1: 'Delhi', 2: 'Kolkata', 3: 'Bangalore', 4: 'Noida'}
raja
Published on 11-Mar-2021 09:38:07
Advertisements