Our use case is that if a key doesn't exist in the dictionary and we are trying to fetch the value against that key then a list with only that key should be returned as the default value.
Below is an example:
>>> dic = defaultdict(<function 'custom_default_function'>, {1: [1,2,6], 3: [3,6,8]})
>>> print(dic[1])
[1,2,6]
>>> print(dic[5])
[5]
In case of key with value 1
the output is completely fine as the key is there in dic. But for the case when we trying to look for key 5
then the default value that the code must print should be [5]
i.e a list with only key as an element inside it.
I tried to write a default function but am not getting on how to pass parameter to the default function.
def default_function(key):
return key
# Defining the dict
d = defaultdict(default_function)
d[1] = [1,4]
d[2] = [2,3]
print(d[4]) # This will throw error as the positional argument for default_function is not missing
Where am I going wrong and how can I resolve this using defaultdict in Python?