Python – Alternate Default Key Value

Sometimes, while working with Python Dictionaries, we can have problem in which we need to assign a particular value to a particular key, but in absence, require the similar’s key’s value but from different dictionary. This problem can have applications in domain of web development. Let’s discuss certain ways in which this task can be performed.

Input : test_dict = {‘gfg’ : {‘a’ : 1, ‘b’ : 2, ‘c’ : 3}, ‘best’ : {‘a’ : 3, ‘c’ : 4, ‘b’ : 17}}
Output : 17

Input : test_dict = {‘gfg’ : {‘b’ : 1}, ‘best’ : {‘a’ : 3}}
Output : 1

Method #1 : Using loop
This is brute force way in which this task can be performed. In this, we test for a particular dictionary for value, if not present we check the alternate key and assign value.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Alternate Default Key Value
# Using loop
  
# initializing dictionary
test_dict = {'gfg' : {'a' : 1, 'b' : 2, 'c' : 3}, 'best' : {'a' : 3, 'c' : 4}}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# alternate key 
alt_key = 'gfg'
  
# Alternate Default Key Value
# Using loop
if 'b' in test_dict['best']:
    res = test_dict['best']['b']
else :
    res = test_dict[alt_key]['b']
      
# printing result 
print("The required value : " + str(res)) 

chevron_right


Output :



The original dictionary is : {‘gfg’: {‘a’: 1, ‘b’: 2, ‘c’: 3}, ‘best’: {‘a’: 3, ‘c’: 4}}
The required value : 2

 

Method #2 : Using get()
This task can also be performed using this method. We can exploit the capability of get() to render default values in case of absence of values.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Alternate Default Key Value
# Using get()
  
# initializing dictionary
test_dict = {'gfg' : {'a' : 1, 'b' : 2, 'c' : 3}, 'best' : {'a' : 3, 'c' : 4}}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# alternate key 
alt_key = 'gfg'
  
# Alternate Default Key Value
# Using get()
res = test_dict.get('best').get('b', test_dict.get(alt_key)['b'])
      
# printing result 
print("The required value : " + str(res)) 

chevron_right


Output :

The original dictionary is : {‘gfg’: {‘a’: 1, ‘b’: 2, ‘c’: 3}, ‘best’: {‘a’: 3, ‘c’: 4}}
The required value : 2




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.