Python – Initialize dictionary keys with Matrix

Sometimes, while working with Python Data, we can have a problem in which we need to construct an empty mesh of dictionaries for further population of data. This problem can have applications in many domains which include data manipulation. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using list comprehension
This is one of the way in which this task can be performed. In this, we initialize the dictionary keys with empty mesh with N by iterating using list comprehension.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Initialize dictionary keys with Matrix
# Using list comprehension
  
# initializing N
num = 4
  
# Initialize dictionary keys with Matrix
# Using list comprehension
res = {'gfg': [[] for _ in range(num)], 'best': [[] for _ in range(num)]}
  
# printing result 
print("The Initialized dictionary : " + str(res)) 

chevron_right


Output :

The Initialized dictionary : {'gfg': [[], [], [], []], 'best': [[], [], [], []]}

 

Method #2 : Using deepcopy()
This task can also be performed using deepcopy(). In this, we perform the task of performing copy of each dictionary key as non referenced key.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Initialize dictionary keys with Matrix
# Using deepcopy()
from copy import deepcopy
  
# initializing N
num = 4
  
# Initialize dictionary keys with Matrix
# Using deepcopy()
temp = [[] for idx in range(num)]
res = {'gfg': deepcopy(temp), 'best': deepcopy(temp)}
  
# printing result 
print("The Initialized dictionary : " + str(res)) 

chevron_right


Output :

The Initialized dictionary : {'gfg': [[], [], [], []], 'best': [[], [], [], []]}



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.