1

同じキーを追加するときにpython dictの値を合計するにはどうすればよいですか?

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

上記の後、 の値はd['key1']30 になるはずです。

これは可能ですか?

4

4 に答える 4

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
于 2013-06-11T11:44:00.443 に答える
4
from collections import defaultdict
d = defaultdict(int)
d['key1'] += 20
于 2013-06-11T11:43:39.187 に答える
0
try:
   dict[key1]+=20 #The value you wanted
except KeyError:
   dict[key1]=10 #The initial Value
于 2013-06-11T11:44:41.697 に答える