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

asked Jan 17, 2016 at 2:57
4
  • 3
    What would a default key be? How would you access a default key? Commented Jan 17, 2016 at 2:59
  • @AChampion, thanks for the reply. I do not get your points, what do you mean default key? Do you mean default value? Commented Jan 17, 2016 at 2:59
  • @AChampion, thanks for the clarification. If you could add a reply, I will mark it as answered to benefit more people. Thanks. Commented Jan 17, 2016 at 3: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: stackoverflow.com/a/19189356/2337736 Or, for a trivial example, fives = defaultdict(lambda : 5) will product a defaultdict where the default value is 5. Commented Jan 17, 2016 at 3:04

1 Answer 1

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
answered Jan 17, 2016 at 3:05
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks AChampion for all the help, mark your reply as answer. :)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.