python-3.x - 将值累积添加到python字典

标签 python-3.x dictionary

假设,我有一本字典

key={'a':5}

现在,我想在不覆盖当前值的情况下向其累加值,而是在其上添加值。如何做? 我举个例子:

for post in doc['post']:
    if 'wow' in post:
        value=2
        for reactor in post['wow']['reactors']:
            dict_of_reactor_ids.update({reactor['img_id']:value})
    if  'sad' in post:
        value=2
        for reactor in post['sad']['reactors']:
            dict_of_reactor_ids.update({reactor['img_id']:value})

假设字典在第一次迭代时是这样的

dict_of_reactor_ids={101:2,102:1}

现在我想将 101 键的值增加 3,那么该怎么做。

dict_of_reactor_ids={101:5,102:1}

现在在 post 的第二次迭代中,我想将值添加到字典中的当前值而不覆盖当前值。
我已经尝试过更新方法,但我认为它只是更新了整个值而不是添加到它上。

最佳答案

听起来像是 Counter 的典型案例:

>>> from collections import Counter
>>> c = Counter()
>>> c["a"] += 1 # works even though "a" is not yet present
>>> c.update({"a": 2, "b": 2}) # possible to do multiple updates
{"a": 3, "b": 2}

在您的情况下,好处是即使键不存在(默认值为 0),它也能正常工作,并且它允许一次更新多个值,而更新普通 dict 会覆盖您注意到的值。

关于python-3.x - 将值累积添加到python字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52029520/

相关文章:

Python 正则表达式反向引用命名组

python-3.x - 我将如何使用 ffpyplayer 播放视频流?

java - 当设备中安装了 .apk 时,谷歌地图无法工作

python - 从文本文件 PYTHON 填充字典

c# - map 生成器的渐变圆圈

python - 冒泡错误条件的pythonic方法是什么

python-3.x - xarray 相当于 Pandas 减法/加法

python - 分别安装 Python 2 和 3

java - 如何在java中对hashmap进行排序?

python - 字典理解错误