累计将值添加到python字典 [英] Cumulatively add values to python dictionary

查看:277
本文介绍了累计将值添加到python字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有字典

key={'a':5}

现在,我想向其累加值,而不覆盖当前值但要添加当前值。如何执行?
我正在举一个实例:

Now ,I want to add values to it cumulatively without overwriting the current value but adding on to it.How to do it? I am giving an instance:

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})

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

Suppose if the dictionary is like this in first iteration

dict_of_reactor_ids={101:2,102:1}

,现在我想将101键的值增加3,然后执行此操作。

and NOW I want to increase the value of 101 key by 3 ,then how to do that.

dict_of_reactor_ids={101:5,102:1}

现在在第二次发布中,我想添加到字典中的当前值而不覆盖当前值。

我尝试了update方法,但我认为它只是更新了整个值

Now in second iteration of post ,I want to add values to the current values in dictionary without overwriting the current value.
I have tried update method but I think it just updates the whole value instead of adding onto it.

推荐答案

听起来像计数器

>>> 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 进行更新将覆盖该值。

In your case the benefit is that it works even when the key is not already in there (default value is 0), and it allows updates of multiple values at once, whereas update on a normal dict would overwrite the value as you've noticed.

这篇关于累计将值添加到python字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆