Open In App

Python – Alternate Default Key Value

Improve
Improve
Like Article
Like
Save
Share
Report

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. 

Python3




# 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))


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. 

Python3




# 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))


Output : 

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

Method #3 : Using list comprehension and min()

Approach

we use a list comprehension to extract the values of the key ‘b’ from each dictionary in the dictionary values. We then use the min() function to get the minimum value, which is the required default value.

Algorithm

1. Use a list comprehension to extract the values of the key ‘b’ from each dictionary in the dictionary values.
2. Use the filter() function to remove None values from the list.
3. Use the min() function to get the minimum value, which is the required default value.

Python3




def get_default_value(test_dict):#define testdict
    values = [d.get('b') for d in test_dict.values()]#get values
    values = list(filter(None, values))#filter values
    default_value = min(values) if values else None#get min value
    return default_value#return result
test_dict = {'gfg' : {'a' : 1, 'b' : 2, 'c' : 3}, 'best' : {'a' : 3, 'c' : 4, 'b' : 17}}
print(get_default_value(test_dict))#print result


Output

2

Time Complexity: O(n) – iterating through the values of the dictionary takes n time complexity.
Space Complexity: O(n) – creating a list to store the extracted values of the key ‘b’.

METHOD 4: Using defaultdict 

APPROACH:

The approach taken in this code is to use a defaultdict of defaultdicts to create a new dictionary with the desired default value for a particular key in all nested dictionaries. First, a defaultdict of defaultdicts is initialized, with the default value set to the desired default value. Then, for each key-value pair in the original dictionary, the value (which is a nested dictionary) is updated into the new defaultdict. Since the defaultdicts are used, any missing keys in the nested dictionary will be automatically populated with the default value.

ALGORITHM:

1.Initialize a defaultdict of defaultdicts with the desired default value
2.For each key-value pair in the original dictionary:
a. Update the nested dictionary into the new defaultdict
3.Return the new defaultdict

Python3




from collections import defaultdict
 
def set_default(dictionary, key, default):
    nested_dict = defaultdict(lambda: defaultdict(lambda: default))
    for k, v in dictionary.items():
        nested_dict[k].update(v)
    return nested_dict[key][key]
 
# Example usage
original_dict = {'gfg': {'a': 1, 'b': 2, 'c': 3}, 'best': {'a': 3, 'c': 4}}
required_value = 2
result = set_default(original_dict, 'b', required_value)
print(result)


Output

2

Time complexity: O(n*m), where n is the number of key-value pairs in the original dictionary and m is the average number of key-value pairs in each nested dictionary.

Auxiliary Space: O(n*m), since the new defaultdict of defaultdicts will contain the same number of key-value pairs as the original dictionary.

METHOD 5: Using reduce():
Algorithm:

  1. Initialize nested_dict to the input dictionary.
  2. Iterate over the characters in the input key using reduce.
  3. At each iteration, set the value of nested_dict for the current character to a new default dictionary with the default value.
  4. Return the value of the required key from the nested_dict.

Python3




from functools import reduce
from collections import defaultdict
 
def set_default(dictionary, key, default):
    nested_dict = reduce(lambda d, k: d.setdefault(k, defaultdict(lambda: default)), key, dictionary)
    return nested_dict[key]
 
# Example usage
original_dict = {'gfg': {'a': 1, 'b': 2, 'c': 3}, 'best': {'a': 3, 'c': 4}}
# printing original dictionary
print("The original dictionary is : " + str(original_dict))
  
required_value = 2
res = set_default(original_dict, 'b', required_value)
 
# printing result
print("The required value : " + str(res))
#This code is contributed by Jyothi pinjala.


Output

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

Time Complexity:

The reduce function iterates over each character in the input key, so the time complexity of set_default is O(n), where n is the length of the input key.
The setdefault method on a dictionary has a time complexity of O(1) on average, so the overall time complexity of the function is O(n).
Space Complexity:

The nested_dict dictionary is initially a copy of the input dictionary, so it has the same space complexity as the input, which is O(m), where m is the number of keys in the input dictionary.
The reduce function creates new default dictionaries for each key in the input key, so the maximum depth of the nested_dict dictionary is equal to the length of the input key. Therefore, the space complexity of the function is O(m * k), where k is the length of the input key.



Last Updated : 21 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads