Paul Manta
Paul Manta

Reputation: 31577

Python `defaultdict`: Use default when setting, but not when getting

Is there any way I can make a collections.defaultdict return a default constructed object when I set it...

foo = defaultdict(list)
foo[3].append('dsafdasf')

... but not when I try to access it?

try:
   for word in foo[None]:
       print(word)
except KeyError:
    pass

Upvotes: 1

Views: 465

Answers (2)

Marcin
Marcin

Reputation: 49826

No, because your example of "setting it" is actually an example of getting an unused slot.

Upvotes: 3

jcollado
jcollado

Reputation: 40384

I think that what you're looking for is something like this:

>>> foo = {}
>>> foo.setdefault(3, []).append('dsafdasf') # Appends to default value
>>> foo[None] # Raises a KeyError exception

That is, instead of using collections.defaultdict, you could use a regular dictionary and use setdefault method when you need to assign a default and item access when you need an exception to be raised for missing keys.

Upvotes: 9

Related Questions