Initialize Dictionary keys with Matrix in Python

Dictionary keys can be initialized with matrix values using several Python methods. A matrix in Python is typically represented as a list of lists, where each inner list represents a row or column of data.

What is Matrix Initialization in Dictionaries?

Matrix initialization means creating dictionary keys where each value is a matrix structure (list of lists). This is useful for storing multi-dimensional data organized by categories.

Using While Loop and append() Method

This method iterates through dictionary keys and appends empty lists to create matrix structures ?

# Initialize dictionary with empty lists
matrix_dict = {'A': [], 'B': [], 'C': []}
n = 3  # Number of rows

# Add empty lists to create matrix structure
i = 0
while i < n:
    matrix_dict['A'].append([])
    matrix_dict['B'].append([])
    matrix_dict['C'].append([])
    i += 1

print("Dictionary with matrix structure:")
print(matrix_dict)
Dictionary with matrix structure:
{'A': [[], [], []], 'B': [[], [], []], 'C': [[], [], []]}

Using fromkeys() Method

The fromkeys() method creates a dictionary with specified keys and default values. However, be careful with mutable objects as they share references ?

# Create dictionary with matrix structure using fromkeys
keys = [1, 2, 3, 4, 5]
matrix_dict = dict.fromkeys(keys, [[]])

# Adding to one key affects all (shared reference issue)
matrix_dict[1].append([])
print("Dictionary after modification:")
print(matrix_dict)
Dictionary after modification:
{1: [[], []], 2: [[], []], 3: [[], []], 4: [[], []], 5: [[], []]}

Using List Comprehension

List comprehension provides a clean way to create dictionary keys with independent matrix structures ?

# Using list comprehension to create independent matrices
keys = {"x", "y", "z"}
matrix_dict = {k: [] for k in keys}

# Add some matrix data
for key in matrix_dict:
    matrix_dict[key] = [[] for _ in range(2)]

print("Dictionary with matrix structure:")
print(matrix_dict)
Dictionary with matrix structure:
{'y': [[], []], 'z': [[], []], 'x': [[], []]}

Using deepcopy() Method

The deepcopy() method creates independent copies of matrix structures, avoiding reference sharing issues ?

from copy import deepcopy

# Create base matrix structure
n = 3
base_matrix = [[] for _ in range(n)]

# Create dictionary with independent matrix copies
matrix_dict = {
    'A': deepcopy(base_matrix), 
    'B': deepcopy(base_matrix), 
    'C': deepcopy(base_matrix)
}

print("Dictionary with independent matrices:")
print(matrix_dict)
Dictionary with independent matrices:
{'A': [[], [], []], 'B': [[], [], []], 'C': [[], [], []]}

Practical Example with Data

Here's a complete example showing how to initialize and populate matrix dictionaries with actual data ?

# Initialize dictionary with matrix data
students = ['Alice', 'Bob', 'Charlie']
subjects = {student: [] for student in students}

# Add grade matrices (rows=tests, columns=subjects)
for student in subjects:
    # Each student has 2 tests with 3 subject scores
    subjects[student] = [[85, 90, 78], [88, 92, 82]]

print("Student grade matrices:")
for student, grades in subjects.items():
    print(f"{student}: {grades}")
Student grade matrices:
Alice: [[85, 90, 78], [88, 92, 82]]
Bob: [[85, 90, 78], [88, 92, 82]]
Charlie: [[85, 90, 78], [88, 92, 82]]

Comparison

Method Independence Best For
While Loop + append() Yes Manual control over structure
fromkeys() No (shared references) Simple initialization (be careful!)
List Comprehension Yes Clean, readable code
deepcopy() Yes Complex structures

Conclusion

Use list comprehension for clean, independent matrix initialization. Use deepcopy() when working with complex nested structures. Avoid fromkeys() with mutable objects due to reference sharing issues.

---
Updated on: 2026-03-27T12:18:27+05:30

418 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements