- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to convert list to dictionary in Python?
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
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
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'}
Advertisements