擅长:python、mysql、java
<p>首先,我使用列表而不是元组作为字典条目。主要的区别在于列表是可变的,而元组不是可变的。</p>
<p>我认为<a href="http://docs.python.org/library/collections.html#collections.defaultdict">^{<cd1>}</a>是解决这个问题的好方法:</p>
<pre><code>from collections import defaultdict
customers = defaultdict(list)
</code></pre>
<p>您可以像这样添加条目(当然,在您的情况下,您将在循环中这样做):</p>
<pre><code>customers['customer1'].append(('milk', 3))
customers['customer1'].append(('bread', 5))
customers['customer2'].append(('cereal', 7))
</code></pre>
<p>结果是:</p>
<pre><code>>>> print dict(customers)
{'customer1': [('milk', 3), ('bread', 5)], 'customer2': [('cereal', 7)]}
</code></pre>