Python – Mapping Matrix with Dictionary

When working with matrices (lists of lists) in Python, you often need to map numerical values to meaningful strings using a dictionary. This technique is useful for converting coded data into readable format.

Basic Matrix Mapping

Here's how to map matrix elements using a dictionary with nested loops ?

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

print("Original matrix:")
print(my_matrix)

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

# Map matrix elements
result = []
for row in my_matrix:
    mapped_row = []
    for element in row:
        mapped_row.append(map_dict[element])
    result.append(mapped_row)

print("Mapped matrix:")
print(result)
Original matrix:
[[2, 4, 3], [4, 1, 3], [2, 1, 3, 4]]
Mapped matrix:
[['Python', 'learn', 'to'], ['learn', 'fun', 'to'], ['Python', 'fun', 'to', 'learn']]

Using List Comprehension

A more concise approach using nested list comprehension ?

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

# One-liner mapping
result = [[map_dict[element] for element in row] for row in my_matrix]

print("Original matrix:")
print(my_matrix)
print("Mapped matrix:")
print(result)
Original matrix:
[[2, 4, 3], [4, 1, 3], [2, 1, 3, 4]]
Mapped matrix:
[['Python', 'learn', 'to'], ['learn', 'fun', 'to'], ['Python', 'fun', 'to', 'learn']]

Handling Missing Keys

Use get() method to handle keys that might not exist in the dictionary ?

my_matrix = [[2, 4, 5], [1, 3, 6]]  # 5 and 6 not in dictionary
map_dict = {2: "Python", 1: "fun", 3: "to", 4: "learn"}

# Safe mapping with default values
result = [[map_dict.get(element, "unknown") for element in row] for row in my_matrix]

print("Matrix with unmapped values:")
print(my_matrix)
print("Safely mapped matrix:")
print(result)
Matrix with unmapped values:
[[2, 4, 5], [1, 3, 6]]
Safely mapped matrix:
[['Python', 'learn', 'unknown'], ['fun', 'to', 'unknown']]

Comparison

Method Readability Error Handling
Nested loops Clear for beginners Requires try-except
List comprehension Concise Requires try-except
Using get() Moderate Built-in default values

Conclusion

Matrix mapping with dictionaries transforms numerical data into meaningful strings. Use nested loops for clarity, list comprehension for conciseness, or get() method for safer mapping with default values.

Updated on: 2026-03-26T01:24:24+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements