Python:list()作为字典的默认值 [英] Python: list() as default value for dictionary
问题描述
我有如下的Python代码:
I have Python code that looks like:
if key in dict:
dict[key].append(some_value)
else:
dict[key] = [some_value]
但是我认为应该有一些方法可以解决这个'if'语句.我尝试过
but I figure there should be some method to get around this 'if' statement. I tried
dict.setdefault(key, [])
dict[key].append(some_value)
和
dict[key] = dict.get(key, []).append(some_value)
,但都抱怨"TypeError:无法散列的类型:'list'".有什么建议吗?谢谢!
but both complain about "TypeError: unhashable type: 'list'". Any recommendations? Thanks!
推荐答案
最好的方法是使用 collections.defaultdict
,默认值为list
from collections import defaultdict
dct = defaultdict(list)
然后只使用:
dct[key].append(some_value)
,如果键尚未在映射中,则词典将为您创建一个新列表. collections.defaultdict
是dict
的子类,否则表现得像普通的dict
对象.
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.
使用标准dict
时,dict.setdefault()
会为您正确设置dct[key]
为默认值,因此该版本应该可以正常工作.您可以使用.append()
链接该呼叫:
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']}
但是,通过使用dct[key] = dct.get(...).append()
,您可以替换 dct[key]
的值,并输出.append()
,即None
.
However, by using dct[key] = dct.get(...).append()
you replace the value for dct[key]
with the output of .append()
, which is None
.
这篇关于Python:list()作为字典的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!