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

限于喜欢 提交于 2020-05-30 07:33:06

问题


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

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/9224284/python-defaultdict-use-default-when-setting-but-not-when-getting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!