Python: list() as default value for dictionary

社会主义新天地 提交于 2019-11-27 15:44:20

问题


I have Python code that looks like:

if key in dict:
  dict[key].append(some_value)
else:
  dict[key] = [some_value]

but I figure there should be some method to get around this 'if' statement. I tried

dict.setdefault(key, [])
dict[key].append(some_value)

and

dict[key] = dict.get(key, []).append(some_value)

but both complain about "TypeError: unhashable type: 'list'". Any recommendations? Thanks!


回答1:


The best method is to use collections.defaultdict with a list default:

from collections import defaultdict
dct = defaultdict(list)

Then just use:

dct[key].append(some_value)

and the dictionary will create a new list for you if the key is not yet in the mapping. collections.defaultdict is a subclass of dict and otherwise behaves just like a normal dict object.

When using a standard dict, dict.setdefault() correctly sets dct[key] for you to the default, so that version should have worked just fine. You can chain that call with .append():

>>> dct = {}
>>> dct.setdefault('foo', []).append('bar')  # returns None!
>>> dct
{'foo': ['bar']}

However, by using dct[key] = dct.get(...).append() you replace the value for dct[key] with the output of .append(), which is None.



来源:https://stackoverflow.com/questions/17755996/python-list-as-default-value-for-dictionary

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