Skip to main content
 首页 » 编程设计

python之Python 字典中的求和值

2025年05月04日11arxive

当我添加相同的键时,如何对 python 字典中的值求和?

d = {'key1':10,'key2':14,'key3':47} 
d['key1'] = 20 

在上面之后 d['key1'] 的值应该是 30。

这可能吗?

请您参考如下方法:

您可以使用collections.Counter:

>>> from collections import Counter 
>>> d =Counter() 
>>> d.update({'key1':10,'key2':14,'key3':47}) 
>>> d['key1'] += 20 
>>> d['key4'] += 50  # Also works for keys that are not present 
>>> d 
Counter({'key4': 50, 'key3': 47, 'key1': 30, 'key2': 14}) 

计数器有一些优点:

>>> d1 = Counter({'key4': 50, 'key3': 4}) 
#You can add two counters 
>>> d.update(d1) 
>>> d 
Counter({'key4': 100, 'key3': 51, 'key1': 30, 'key2': 14}) 

您可以使用 most_common() 获取已排序项目的列表(基于值):

>>> d.most_common() 
[('key4', 100), ('key3', 51), ('key1', 30), ('key2', 14)] 

时序比较:

>>> keys = [ random.randint(0,1000) for _ in xrange(10**4)] 
>>> def dd():                              
    d = defaultdict(int) 
    for k in keys: 
        d[k] += 10 
...          
>>> def count():                              
    d = Counter() 
    for k in keys: 
        d[k] += 10 
...          
>>> def simple_dict(): 
...     d = {} 
...     for k in keys: 
...         d[k] = d.get(k,0) + 10 
...          
>>> %timeit dd() 
100 loops, best of 3: 3.47 ms per loop 
>>> %timeit count() 
100 loops, best of 3: 10.1 ms per loop 
>>> %timeit simple_dict() 
100 loops, best of 3: 5.01 ms per loop