+

Python | Safe access to nested dictionary keys

Method # 1: Using a nested get()

This method is used to solve this particular problem, we just use the get functionality () for validation and assignment in the absence of a value to achieve this specific objective. Simply returns non-error None if any key is missing.

# Python3 code to demonstrate how it works
# Safe access to nested dictionary key
# Using nested get ()

 
# initializing dictionary

test_dict = { `Gfg` : { `is` : ` best` }}

  
# print original dictionary

print ( " The original dictionary is: " + str (test_dict ))

 
# using nested get ()
# Secure access to the nested dictionary key

res = test_dict.get ( `Gfg` , {}). get ( `is` )

  
# print result

print ( "The nested safely accessed value is: " + str (res))

Exit:

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

Method # 2: Using reduce () + lambda

A combination of the above functions can be used to accomplish this specific task. It just checks the use of the lambda function for the available keys. The advantage of this method is that you can request more than 1 key at the same time, i.e. more nested level keys, but the negative is that it only works with Python2.

# Python code to demonstrate how it works
# Safely access the nested dictionary key
# Using Reduce () + Lambda

 
# initializing dictionary

test_dict = { `Gfg` : { `is` : ` best` }}

 
# print the original dictionary

print ( " The original dictionary is: " + str (test_dict))

 
# using Reduce () + lambda
# Safe access to nested dictionary key

keys = [ `Gfg` , `is` ]

res = reduce ( lambda val, key: val.get (key) if val else None , keys, test_dict)

< code class = "undefined spaces">  
# print 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                                        
             
                
Get Solution for free from DataCamp guru