1

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. How do I do this?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
accelke
  • 193
  • 1
  • 3
  • 11
  • 2
    Note that the argument to `defaultdict` should be *callable*; `defaultdict(lambda: float('-inf'))` would work, for instance. See e.g. http://stackoverflow.com/q/5029934/3001761 (not *precisely* a duplicate, but identical underlying issue). – jonrsharpe Apr 27 '15 at 16:52
  • 1
    @jonrsharpe thats an answer not a comment :P – Joran Beasley Apr 27 '15 at 16:54
  • @JoranBeasley I was looking for a dupe, but I couldn't find a really good one... – jonrsharpe Apr 27 '15 at 16:58
  • This should be a duplicate of [Python Argument Binders](https://stackoverflow.com/questions/277922/python-argument-binders) but I am out of close votes today. – Karl Knechtel Sep 04 '22 at 05:46

1 Answers1

14

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 Python: defaultdict of defaultdict?).

Community
  • 1
  • 1
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • Thanks that worked. I got confused since when making the default an `int` I don't need to do that. – accelke Apr 27 '15 at 17:03
  • @accelke no, because `int` is callable and returns the default value to use; I've included this example in my answer. – jonrsharpe Apr 27 '15 at 17:04
  • thanks, this advice helped me create a dict with [0,0] as the default value: `presults=defaultdict(lambda:[0,0])` – jimh Aug 15 '17 at 07:49