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