Search code examples
pythonpython-3.xdefaultdict

Trying to get a list with only key value as the defaultvalue in Python using defaultdict


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?


Solution

  • 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: