擅长:python、mysql、java
<p>我想你想要的是一个<a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow">^{<cd1>}</a>。这允许您指定一个默认的factory callable,如果dict中不存在键,它将返回(例如)一个新的空列表;否则,它将返回找到的值。你知道吗</p>
<p>例如:</p>
<pre><code>In [1]: from collections import defaultdict
In [2]: example = defaultdict(list)
In [3]: example['foo']
Out[3]: []
In [4]: example['foo'] += [1, 2, 3, 4, 5]
In [5]: example['foo']
Out[5]: [1, 2, 3, 4, 5]
In [6]: example['bar']
Out[6]: []
</code></pre>