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
Python – Convert List to Index and Value dictionary
When you need to convert a list into a dictionary containing separate index and value arrays, Python's enumerate() function provides an elegant solution. This approach creates a structured dictionary with index and values keys.
Basic Example
Here's how to convert a list to an index-value dictionary ?
my_list = [32, 0, 11, 99, 223, 51, 67, 28, 12, 94, 89]
print("The list is:")
print(my_list)
my_list.sort(reverse=True)
print("The sorted list is:")
print(my_list)
index, value = "index", "values"
my_result = {index : [], value : []}
for id, vl in enumerate(my_list):
my_result[index].append(id)
my_result[value].append(vl)
print("The result is:")
print(my_result)
The list is:
[32, 0, 11, 99, 223, 51, 67, 28, 12, 94, 89]
The sorted list is:
[223, 99, 94, 89, 67, 51, 32, 28, 12, 11, 0]
The result is:
{'index': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'values': [223, 99, 94, 89, 67, 51, 32, 28, 12, 11, 0]}
Alternative Method: Using List Comprehension
A more concise approach using list comprehensions ?
my_list = [32, 0, 11, 99, 223]
# Create index-value dictionary in one step
result = {
'index': [i for i, _ in enumerate(my_list)],
'values': [val for _, val in enumerate(my_list)]
}
print("Original list:", my_list)
print("Index-Value dictionary:", result)
Original list: [32, 0, 11, 99, 223]
Index-Value dictionary: {'index': [0, 1, 2, 3, 4], 'values': [32, 0, 11, 99, 223]}
How It Works
The enumerate() function returns pairs of (index, value) for each element in the list. The loop iterates through these pairs and appends the index to the 'index' list and the value to the 'values' list within the result dictionary.
Practical Use Case
This pattern is useful when you need to track both positions and values separately, such as for data analysis or creating lookup tables ?
fruits = ['apple', 'banana', 'cherry', 'date']
fruit_dict = {'index': [], 'values': []}
for i, fruit in enumerate(fruits):
fruit_dict['index'].append(i)
fruit_dict['values'].append(fruit)
print("Fruit dictionary:", fruit_dict)
print("First fruit at index:", fruit_dict['index'][0], "is", fruit_dict['values'][0])
Fruit dictionary: {'index': [0, 1, 2, 3], 'values': ['apple', 'banana', 'cherry', 'date']}
First fruit at index: 0 is apple
Conclusion
Converting a list to an index-value dictionary using enumerate() provides a structured way to maintain both positional information and values. This approach is particularly useful for data processing tasks where you need to track element positions alongside their values.
