Python – Convert List to Index and Value dictionary

PythonServer Side ProgrammingProgramming

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.

raja
Published on 13-Sep-2021 07:28:01
Advertisements