当我添加相同的密钥时,如何对python dict中的值求和?
d = {'key1':10,'key2':14,'key3':47}
d['key1'] = 20
在上述之后,d['key1']
的值应为30。
这可能吗?
答案 0 :(得分:5)
您可以使用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
答案 1 :(得分:4)
from collections import defaultdict
d = defaultdict(int)
d['key1'] += 20
答案 2 :(得分:0)
try:
dict[key1]+=20 #The value you wanted
except KeyError:
dict[key1]=10 #The initial Value
答案 3 :(得分:0)
d = {'key1':10,'key2':14,'key3':47}
解决方案在一行中,当我们添加相同的键时,对python dict中的值求和:
d ['key1'] = dict.get('key1',0)+ 20
<强>解释强>
dict.get('key1',0)
如果在dict中找到,则返回键值,否则返回默认值为0