Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to convert list to dictionary in Python?
Converting a list to a dictionary in Python is a common operation, especially when you have paired data elements. This article demonstrates different methods to transform a list where odd position elements become keys and even position elements become values.
Understanding the Conversion
Given a list like [1, 'Delhi', 2, 'Kolkata', 3, 'Bangalore', 4, 'Noida'], we want to create a dictionary where:
- Elements at index 0, 2, 4... become keys
- Elements at index 1, 3, 5... become values
The result would be: {1: 'Delhi', 2: 'Kolkata', 3: 'Bangalore', 4: 'Noida'}
Using Loop Iteration
This method iterates through the list with a step of 2, pairing consecutive elements ?
def convert_list_to_dict(data):
result = {}
for i in range(0, len(data), 2):
result[data[i]] = data[i+1]
return result
cities = [1, 'Delhi', 2, 'Kolkata', 3, 'Bangalore', 4, 'Noida']
print(convert_list_to_dict(cities))
{1: 'Delhi', 2: 'Kolkata', 3: 'Bangalore', 4: 'Noida'}
Using zip() with Iterator
The zip() function with an iterator provides a more elegant solution by pairing adjacent elements ?
def convert_list_to_dict(data):
iterator = iter(data)
return dict(zip(iterator, iterator))
cities = [1, 'Delhi', 2, 'Kolkata', 3, 'Bangalore', 4, 'Noida']
print(convert_list_to_dict(cities))
{1: 'Delhi', 2: 'Kolkata', 3: 'Bangalore', 4: 'Noida'}
Using Dictionary Comprehension
A concise one-liner approach using dictionary comprehension ?
cities = [1, 'Delhi', 2, 'Kolkata', 3, 'Bangalore', 4, 'Noida']
result = {cities[i]: cities[i+1] for i in range(0, len(cities), 2)}
print(result)
{1: 'Delhi', 2: 'Kolkata', 3: 'Bangalore', 4: 'Noida'}
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| Loop Iteration | High | Good | Beginners, complex logic |
| zip() with Iterator | Medium | Excellent | Memory efficiency |
| Dictionary Comprehension | Medium | Good | Concise code |
Conclusion
Use zip() with iterator for the most efficient solution, dictionary comprehension for concise code, or loop iteration when you need maximum clarity and control over the conversion process.
