Python | Creating Multidimensional dictionary
Last Updated :
27 Apr, 2023
Sometimes, while working with Python dictionaries we need to have nested dictionaries. But the issue is that, we have to declare before initializing a value in nested dictionary. Let’s resolve this particular problem via methods discussed in this article.
Method #1 : Using setdefault()
This function is used to define an empty dictionary on 1st nested level of dictionary to make it 2D. In this case there is no need to define explicit dictionaries at that level of dictionary.
Python3
test_dict = {}
print ( "The original dictionary : " + str (test_dict))
test_dict.setdefault( 1 , {})[ 4 ] = 7
print ( "Dictionary after nesting : " + str (test_dict))
|
Output :
The original dictionary : {}
Dictionary after nesting : {1: {4: 7}}
Time Complexity: O(n), where n is the length of the list test_dict
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #2 : Using defaultdict()
One can achieve the creation of multi nesting using defaultdict(). Not only at one level, but till N level the nesting can be achieved using this. Drawback is that it creates the defaultdict objects.
Python3
from collections import defaultdict
def multi_dict(K, type ):
if K = = 1 :
return defaultdict( type )
else :
return defaultdict( lambda : multi_dict(K - 1 , type ))
test_dict = {}
print ( "The original dictionary : " + str (test_dict))
test_dict = multi_dict( 3 , int )
test_dict[ 2 ][ 3 ][ 4 ] = 1
print ( "Dictionary after nesting : " + str ( dict (test_dict)))
|
Output :
The original dictionary : {}
Dictionary after nesting : {2: defaultdict(<function multi_dict.<locals>.<lambda> at 0x7f8707a54158>, {3: defaultdict(<class 'int'>, {4: 1})})}
Share your thoughts in the comments
Please Login to comment...