Lin Ma
Lin Ma

Reputation: 10159

initialize defaultdict in Python

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

Upvotes: 1

Views: 1752

Answers (1)

AChampion
AChampion

Reputation: 30288

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

Upvotes: 5

Related Questions