
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
Mapping Matrix with Dictionary in Python
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.
Advertisements