擅长:python、mysql、java
<p>不能。Python字典不支持重复键,它将被重写。你知道吗</p>
<p>但是,您可以为它创建一个新的数据类型。你知道吗</p>
<pre><code>class Dictlist(dict):
def __setitem__(self, key, value):
try:
self[key]
except KeyError:
super(Dictlist, self).__setitem__(key, [])
self[key].append(value)
</code></pre>
<p>示例使用</p>
<pre><code>>>> d = dictlist.Dictlist()
>>> d['test'] = 1
>>> d['test'] = 2
>>> d['test'] = 3
>>> d
{'test': [1, 2, 3]}
>>> d['other'] = 100
>>> d
{'test': [1, 2, 3], 'other': [100]}
</code></pre>
<p>使用<code>Dictlist</code>数据类型回答您的问题</p>
<pre><code>dictt = dictlist.Dictlist()
dictt['a'] = 22
dictt['a'] = 33
dictt['c'] = 34
dictt['d'] = 456
lookFor = 'a'
len(dictt['a'])
</code></pre>