-1

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?

Pratap Alok Raj
  • 1,098
  • 10
  • 19

1 Answers1

3

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:

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
  • thanks a lot for the solution, it really helped me a lot. I have one small doubt, when I am trying to inherit collections.defaultdict instead of dict and print the my_dict, I am getting the result as "MyDict(None, {5: [5]})" . Can you please explain me why None is there – Pratap Alok Raj Mar 20 '22 at 13:59
  • `defaultdict` prints the *factory* (i.e. the function that is called in order to create the default argument). – hiro protagonist Mar 20 '22 at 15:34