Initialize Dictionary keys with Matrix in Python


The dictionary is one of the four popular datatypes in Python that has a collection of specific keys with value pair whereas matrix is defined by a rectangular array that consists of rows and columns. In Python, we have some built−in functions such as append(), str(), fromkeys(), dict(), and, deepcopy() will be used to initialize dictionary keys with Matrix.

Syntax

The following syntax is used in the examples

append()

The append() is a built−in method in Python that accepts a single parameter as input to add to the given dictionary at the end.

str()

The built−in function str() converts the value into a string. Hence these strings can be integrated with other strings.

fromkeys()

The fromkeys() is an in−built function in Python that returns the dictionary with key and value pair.

dict()

The built−in function dict() is used to create the dictionary.

deepcopy()

The built−in function deepcopy() is another way to process the elements of dictionary recursively.

Using While Loop and append() Function

The program uses a while loop to iterate through each key from the dictionary and using append it inserts the list to represent the matrix as a value.

Example

In the following example, start the program by initializing the variable named n which will initialize the number of columns in a matrix as a value. Then create the dictionary in the variable dict. Next, initialize the variable i with an initial value that will help to iterate from the beginning key. Then using the while loop it iterates all the key elements from the dictionary and adds the list value to each key by using the built−in function append(). By incrementing it will iterate every key element from the dictionary and display the result with the help of str(dict).

n = 3
# Assigning the key with matrix value
dict = {'A': [], 'B': [], 'C': []}
# Initial value i for iteration
i = 0
while i < n:
    dict['A'].append([])
    dict['B'].append([])
    dict['C'].append([])
# Increment to iterate on each key
    i += 1
# Display the result
print("Dictionary having key with matrix:\n" + str(dict))

Output

 The Initialized dictionary :
 {'A': [[], [], []], 'B': [[], [], []], 'C': [[], [], []]}

Using fromkeys() Function

The program uses built−in functions fromkeys() that help to return the key with value pair whereas append() function adds the second list in order of column to set the matrix value with the key.

Example

In the following example, start the program by using the built−in function fromkeys() with dict to create a dictionary and store it in the variable A. Then add the list to the second column to form the value as a matrix and display the result with the help of variable A.

A = dict.fromkeys([1, 2, 3, 4, 5], [[]])
A[1].append([])
print(A)

Output

 {1: [[], []], 2: [[], []], 3: [[], []], 4: [[], []], 5: [[], []]}

Using List Comprehension

The program uses list comprehension to solve the dictionary keys with Matrix.

Example

In the following example, we will start the program by initializing the dictionary and storing it in the variable keys. It then creates the list of tuples where the first element is set as the key and the second element set as an empty list. Then use the for loop where k variable iterates through keys and set the value as an empty list that defines the key with Matrix. All these processes store it in the variable res. Finally, we are printing the output with the help of a variable named res.

keys = {"x", "y", "z"}
res = dict([(k, []) for k in keys])
print("Dictionary having key with matrix:\n", res)

Output

Dictionary having key with matrix:
 {'x': [], 'y': [], 'z': []}

Using deepcopy()

The program uses a built−in function deepcopy() that store the parameter as the copying process occurs recursively.

Example

In the following example, we will start the program by importing module deepcopy() from the library copy which set the copying reference of the variable. Then initialize the variable n to 5 to set the range of the matrix. Now iterate the empty list according to n value using for loop in the variable mtrx. Next, initialize the dictionary to set the key and value in the variable res. In the pair value, it will use the built−in function deepcopy() that accepts the variable mtrx as a parameter to set the reference and display the result.

# Using deepcopy()
from copy import deepcopy
n = 5
mtrx = [[] for idx in range(n)]
res = {'A': deepcopy(mtrx), 'B': deepcopy(mtrx), 'C': deepcopy(mtrx)}
# Display the result
print("Dictionary having key with matrix:\n" + str(res))

Output

 Dictionary having key with matrix:
{'A': [[], [], [], [], []], 'B': [[], [], [], [], []], 'C': [[], [], [], [], []]}

Conclusion

In this article, we understood the various methods to solve the problem statements. We saw there are two different built−in functions used such as fromkeys() and deepcopy() to return the dictionary key along its value pair. This type of logical building help to solve the problem related to population and real−world statistical data.

Updated on: 14-Aug-2023

106 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements