1

A dumb question after searching for Python Doc, for the constructor of defaultdict, there is only one parameter, which is type of value. Is there a way to specify type of key? I read a few samples and it seems no one specify type of key, and they just specify type of value. And whether it is needed or not -- interested to learn why defaultdict just needs to specify type of value.

thanks in advance, Lin

Lin Ma
  • 9,739
  • 32
  • 105
  • 175
  • 3
    What would a default key be? How would you access a default key? – AChampion Jan 17 '16 at 02:59
  • @AChampion, thanks for the reply. I do not get your points, what do you mean default key? Do you mean default value? – Lin Ma Jan 17 '16 at 02:59
  • @AChampion, thanks for the clarification. If you could add a reply, I will mark it as answered to benefit more people. Thanks. – Lin Ma Jan 17 '16 at 03:03
  • 3
    Note that you're not specifying the "type" of the values. You're specifying a no-argument constructor, which must construct a default value. For instance, see this answer for a way to create an indefinitely nested defaultdict: http://stackoverflow.com/a/19189356/2337736 Or, for a trivial example, `fives = defaultdict(lambda : 5)` will product a `defaultdict` where the default value is 5. – Peter DeGlopper Jan 17 '16 at 03:04

1 Answers1

5

Python is a dynamically typed language, your don't specify types (ignoring the newly added type hints). The argument to defaultdict is a function that returns a value when accessing a key that hasn't been added to the dictionary. Not a type

defaultdict(int)

Is equivalent to:

defaultdict(lambda:int())   # int() returns 0
AChampion
  • 29,683
  • 4
  • 59
  • 75