setting the default string value of Python's collections.defaultdict

吃可爱长大的小学妹 提交于 2019-12-22 01:12:29

问题


I am using Python 3.2.3 and want to change the default returned string value:

from collections import defaultdict
d=defaultdict(str)
d["NonExistent"]

The value returned is ''. How can I change this so that when a key is not found, "unknown" is returned instead of the empty string?


回答1:


The argument to defaultdict is a function (or rather, a callable object) that returns the default value. So you can pass in a lambda that returns your desired default.

>>> from collections import defaultdict
>>> d = defaultdict(lambda: 'My default')
>>> d['junk']
'My default'

Edited to explain lambda:

lambda is just a shorthand for defining a function without giving it a name. You could do the same with an explicit def:

>>> def myDefault():
...     return 'My default'
>>>> d = defaultdict(myDefault)
>>> d['junk']
'My default'

See the documentation for more info.



来源:https://stackoverflow.com/questions/10923334/setting-the-default-string-value-of-pythons-collections-defaultdict

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