Python – Mapping Matrix with Dictionary

PythonServer Side ProgrammingProgramming

When it is required to map the matrix to a dictionary, a simple iteration is used.

Example

Below is a demonstration of the same −

my_list = [[2, 4, 3], [4, 1, 3], [2, 1, 3, 4]]

print("The list :")
print(my_list)

map_dict = {2 : "Python", 1: "fun", 3 : "to", 4 : "learn"}

my_result = []
for index in my_list:
   temp = []
   for element in index:
      temp.append(map_dict[element])
   my_result.append(temp)

print("The result is :")
print(my_result)

Output

The list :
[[2, 4, 3], [4, 1, 3], [2, 1, 3, 4]]
The result is :
[['Python', 'learn', 'to'], ['learn', 'fun', 'to'], ['Python', 'fun', 'to', 'learn']]

Explanation

  • A list of list is defined and displayed on the console.

  • The value for mapping dictionary is defined.

  • An empty list is created.

  • The list is iterated over, and the element from the mapping dictionary is appended to a temp variable (empty list).

  • Otherwise, it is appended to empty list.

  • This is the output that is displayed on the console.

raja
Published on 08-Sep-2021 10:35:14
Advertisements