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
Convert two lists into a dictionary in Python
Python dictionaries store data as key-value pairs, while lists contain a series of values. Converting two lists into a dictionary is a common task where one list provides keys and another provides corresponding values. Python offers several methods to achieve this conversion.
Using zip() Function
The zip() function is the most pythonic and efficient way to combine two lists into a dictionary. It pairs elements from both lists and creates key-value pairs ?
keys = ["Mon", "Tue", "Wed"]
values = [3, 6, 5]
# Given lists
print("Keys:", keys)
print("Values:", values)
# Convert to dictionary using zip
result = dict(zip(keys, values))
print("Dictionary from lists:", result)
Keys: ['Mon', 'Tue', 'Wed']
Values: [3, 6, 5]
Dictionary from lists: {'Mon': 3, 'Tue': 6, 'Wed': 5}
Using Dictionary Comprehension with range()
Dictionary comprehension with range() and len() provides another approach by iterating through indices ?
keys = ["Mon", "Tue", "Wed"]
values = [3, 6, 5]
# Given lists
print("Keys:", keys)
print("Values:", values)
# Convert to dictionary using comprehension
result = {keys[i]: values[i] for i in range(len(keys))}
print("Dictionary from lists:", result)
Keys: ['Mon', 'Tue', 'Wed']
Values: [3, 6, 5]
Dictionary from lists: {'Mon': 3, 'Tue': 6, 'Wed': 5}
Using for Loop with remove()
This approach uses nested loops and removes values from the list. However, it modifies the original list and is less efficient ?
keys = ["Mon", "Tue", "Wed"]
values = [3, 6, 5]
# Given lists
print("Keys:", keys)
print("Values:", values)
# Empty dictionary
result = {}
# Convert to dictionary
for key in keys:
for value in values:
result[key] = value
values.remove(value)
break
print("Dictionary from lists:", result)
Keys: ['Mon', 'Tue', 'Wed']
Values: []
Dictionary from lists: {'Mon': 3, 'Tue': 6, 'Wed': 5}
Comparison
| Method | Efficiency | Readability | Modifies Original? |
|---|---|---|---|
zip() |
High | Excellent | No |
| Dictionary Comprehension | High | Good | No |
| Loop with remove() | Low | Poor | Yes |
Conclusion
The zip() function is the preferred method for converting two lists into a dictionary due to its simplicity and efficiency. Dictionary comprehension is also a good alternative when you need more control over the process.
