Saturday, November 16, 2024
Google search engine
HomeLanguagesPython | Safe access nested dictionary keys

Python | Safe access nested dictionary keys

Sometimes, while working with Python we can have a problem in which we need to get the 2nd degree key of dictionary i.e the nested key. This type of problem is common in case of web development, especially with the advent of NoSQL databases. Let’s discuss certain ways to safely get the nested available key in dictionary.

Method #1 : Using nested get() This method is used to solve this particular problem, we just take advantage of the functionality of get() to check and assign in absence of value to achieve this particular task. Just returns non-error None if any key is not present. 

Python3




# Python3 code to demonstrate working of
# Safe access nested dictionary key
# Using nested get()
 
# initializing dictionary
test_dict = {'Gfg' : {'is' : 'best'}}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# using nested get()
# Safe access nested dictionary key
res = test_dict.get('Gfg', {}).get('is')
 
# printing result
print("The nested safely accessed value is :  " + str(res))


Output : 

The original dictionary is : {'Gfg': {'is': 'best'}}
The nested safely accessed value is :  best

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 reduce() + lambda The combination of above functions can be used to perform this particular task. It just checks using lambda function for the available keys. The plus of this method is that more than 1 key can be queried at once i.e more nested level keys, but the negative is that it does only work with Python2. 

Python




# Python code to demonstrate working of
# Safe access nested dictionary key
# Using reduce() + lambda
 
# initializing dictionary
test_dict = {'Gfg' : {'is' : 'best'}}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# using reduce() + lambda
# Safe access nested dictionary key
keys = ['Gfg', 'is']
res = reduce(lambda val, key: val.get(key) if val else None, keys, test_dict)
 
# printing result
print("The nested safely accessed value is :  " + str(res))


Output : 

The original dictionary is : {'Gfg': {'is': 'best'}}
The nested safely accessed value is :  best

Time Complexity: O(n)
Auxiliary Space: O(1)

Method 3: Use a for loop and check if each key exists in the dictionary

  • Set the variable val equal to the original dictionary test_dict.
  • Start a for loop that iterates through each key in the keys list.
  • Check if the current key exists in the dictionary val using the in operator.
  • If the current key exists in the dictionary, update val to be the value corresponding to that key using dictionary indexing (val[key]).
  • If the current key does not exist in the dictionary, set val to None and break out of the for loop.
  • Print the result of accessing the nested dictionary key safely using the print() function. 

Python3




# initializing dictionary
test_dict = {'Gfg': {'is': 'best'}}
 
# printing original dictionary
print("The original dictionary is : ", test_dict)
 
# using for loop to access nested dictionary key safely
keys = ['Gfg', 'is']
val = test_dict
for key in keys:
    if key in val:
        val = val[key]
    else:
        val = None
        break
 
# printing result
print("The nested safely accessed value is : ", val)


Output

The original dictionary is :  {'Gfg': {'is': 'best'}}
The nested safely accessed value is :  best

Time Complexity: O(n)
Auxiliary Space: O(1)

RELATED ARTICLES

Most Popular

Recent Comments