Home > Enterprise >  Trying to get a list with only key value as the defaultvalue in python using defaultdict
Trying to get a list with only key value as the defaultvalue in python using defaultdict

Time:03-21

Problem statement :-

Whenever, we try to fetch the value against a key, our use case is that is the key doesn't exist in the dictionary 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 amm 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

Could anyone please help me with what am I doing wrong and how can I resolve this using defaultdict in python.

CodePudding user response:

defaultdict will not generate a new value that depends on the key...

you could inherit from dict and overload __missing__:

class MyDict(dict):

    def __init__(self):
        super().__init__()

    def __missing__(self, key):
        self[key] = [key]
        return self[key]

my_dict = MyDict()

print(my_dict[5])  # -> [5]
print(my_dict)     # -> {5: [5]}

there are 2 other answers here that might help:

  • Related