在 python 中初始化或追加字典列表

Initialise or append dictionary list in python

下面的代码片段能否以某种方式简化为一条语句?

if aKey not in aDict:
    aDict[aKey] = [someValue]
else: 
    aDict[aKey].append(someValue)

我可以编写一个接受 aDictaKeysomeValue 的函数,但是有没有办法只使用本机 python 东西来做到这一点?

collections.defaultdict 就是为了这个目的而制作的:

In [1]: import collections

In [2]: d = collections.defaultdict(list)

In [3]: d['key'].append(1)

In [4]: d
Out[4]: defaultdict(<type 'list'>, {'key': [1]})

In [5]: d['key'].append(2)

In [6]: d
Out[6]: defaultdict(<type 'list'>, {'key': [1, 2]})

这里,当你访问一个不存在的键时,它会自动初始化为一个空列表。