gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 05:14:57 25 4
gpt4 key购买 nike

假设,我有一本字典

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com