
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert List to Index and Value Dictionary in Python
When it is required to convert a list into an index value dictionary, the ‘enumerate' and a simple iteration are used.
Example
Below is a demonstration of the same −
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)
Output
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]}
Explanation
A list of integers is defined and is displayed on the console.
The list is sorted in reverse order and is displayed on the console.
The index and values are initialized for display purposes.
The list is iterated over using enumerate, and the index and values are appended to the empty list.
This is the output that is displayed on the console.
Advertisements