Python – Convert List to Index and Value dictionary

PythonServer Side ProgrammingProgramming

Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

Practical Data Science using Python

22 Lectures 6 hours

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.

Updated on 13-Sep-2021 07:28:01