Python:list() 作为字典的默认值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17755996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: list() as default value for dictionary
提问by Fysx
I have Python code that looks like:
我有如下所示的 Python 代码:
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
但我认为应该有一些方法可以绕过这个“if”语句。我试过
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!
但两者都抱怨“TypeError:unhashable type:'list'”。有什么建议吗?谢谢!
采纳答案by Martijn Pieters
The best method is to use collections.defaultdict
with a list
default:
最好的方法是使用collections.defaultdict
一个list
默认值:
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.
如果键不在映射中,字典将为您创建一个新列表。collections.defaultdict
是一个子类,dict
其他方面的行为就像一个普通dict
对象。
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()
:
使用标准时dict
,为您dict.setdefault()
正确设置dct[key]
为默认值,因此该版本应该可以正常工作。您可以使用以下链接链接该调用.append()
:
>>> dct = {}
>>> dct.setdefault('foo', []).append('bar') # returns None!
>>> dct
{'foo': ['bar']}
However, by using dct[key] = dct.get(...).append()
you replacethe value for dct[key]
with the output of .append()
, which is None
.
但是,通过使用,dct[key] = dct.get(...).append()
您可以将for 的值替换为dct[key]
的输出.append()
,即None
。