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
Dictionary with index as value in Python
In this article we will learn how to create a dictionary from a Python list, where the list values become dictionary keys and their positions become the values. This is useful when you need to map elements to their index positions.
Using enumerate with Dictionary Comprehension
The enumerate() function adds a counter to each element in the list. We can use it with dictionary comprehension to create a dictionary where list values become keys and their positions become values ?
Example
days = ['Mon', 'Tue', 'Wed', 'Wed', 11, 11]
# Given list
print("Given list:", days)
# Converting to Dictionary
new_dict = {val: key + 1 for key, val in enumerate(days)}
# Print result
print("Dictionary created with index:", new_dict)
Running the above code gives us the following result −
Given list: ['Mon', 'Tue', 'Wed', 'Wed', 11, 11]
Dictionary created with index: {'Mon': 1, 'Tue': 2, 'Wed': 4, 11: 6}
Note that when there are duplicate elements, only the last occurrence is displayed with its higher index value from among the duplicates.
Using zip and range
Another approach is to use range() to create index values starting from 1, then use zip() to pair list elements with their positions ?
Example
days = ['Mon', 'Tue', 'Wed', 'Wed', 11, 11]
# Given list
print("Given list:", days)
# Converting to Dictionary
new_dict = dict(zip(days, range(1, len(days) + 1)))
# Print result
print("Dictionary created with index:", new_dict)
Running the above code gives us the following result −
Given list: ['Mon', 'Tue', 'Wed', 'Wed', 11, 11]
Dictionary created with index: {'Mon': 1, 'Tue': 2, 'Wed': 4, 11: 6}
Comparison
| Method | Syntax | Best For |
|---|---|---|
enumerate() |
Dictionary comprehension | More Pythonic and readable |
zip() + range() |
Built-in functions | Simple and straightforward |
Handling Zero-based Indexing
If you want zero-based indexing instead of starting from 1 ?
days = ['Mon', 'Tue', 'Wed', 'Thu']
# Zero-based indexing
zero_based = {val: key for key, val in enumerate(days)}
print("Zero-based indexing:", zero_based)
# One-based indexing
one_based = {val: key + 1 for key, val in enumerate(days)}
print("One-based indexing:", one_based)
Zero-based indexing: {'Mon': 0, 'Tue': 1, 'Wed': 2, 'Thu': 3}
One-based indexing: {'Mon': 1, 'Tue': 2, 'Wed': 3, 'Thu': 4}
Conclusion
Both enumerate() and zip() + range() methods effectively convert list elements to dictionary keys with their positions as values. The enumerate() approach is more Pythonic, while zip() + range() is straightforward and easy to understand.
