pythondefaultdict

Defaultdict with values defaulted to negative infinity


I want to create a default dictionary in which the default values are negative infinity. I tried doing defaultdict(float("-inf")) but it is not working:

Traceback (most recent call last):
  File "...", line 2, in <module>
    d = defaultdict(float("-inf"))
        ^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: first argument must be callable or None

How do I do this?


Solution

  • As the traceback specifically tells you:

    >>> from collections import defaultdict
    >>> dct = defaultdict(float('-inf'))
    
    Traceback (most recent call last):
      File "<pyshell#1>", line 1, in <module>
        dct = defaultdict(float('-inf'))
    TypeError: first argument must be callable
    

    and per the documentation (emphasis mine):

    If default_factory [the first argument to defaultdict] is not None, it is called without arguments to provide a default value for the given key, this value is inserted in the dictionary for the key, and returned.

    float('-inf') is not callable. Instead, you could do e.g.:

    dct = defaultdict(lambda: float('-inf'))
    

    providing a callable "lambda expression" that returns the default value. It's for the same reason that you see code with e.g. defaultdict(int) rather than defaultdict(0):

    >>> int()  # callable
    0  # returns the desired default value
    

    You would also get similar issues when e.g. trying to nest defaultdicts within each other (see defaultdict of defaultdict?).