简体   繁体   English

如何增加字典中每个键的值?

[英]How to increment values for each key in dict?

In Python, how to iterate a dict and increment values of each key? 在Python中,如何迭代dict并增加每个键的值?

D = {k1:1, k2:2}

I want D to be {k1:2, k2:3} . 我希望D{k1:2, k2:3}

You can use a dict comprehension to increment each value, then assign it back 您可以使用dict理解来增加每个值,然后将其分配回去

>>> {k: v+1 for k,v in D.items()}
{'k1': 2, 'k2': 3}

You can either modify (also called "mutate") the dictionary D: 您可以修改(也称为“变异”)字典D:

for k in D.keys():
    D[k] = D[k] + 1 

Or you can create a new dictionary and re-assign D to it: 或者,您可以创建一个新词典并为它重新分配D:

D = { k: v+1 for k, v in D.items() }

The difference will become apparent if something else points at D, or if D is very large and takes longer to re-create than to update in-place. 如果其他地方指向D,或者如果D非常大并且重新创建比就地更新花费的时间更长,则差异将变得明显。

D = {"k1":1, "k2":2}

for i in D:
  D[i] += 1

print(D)

Seems to do the trick, I wasnt sure on the k1 / k2 so i made them strings for testing 似乎可以解决问题,我不确定在k1 / k2上是什么,所以我将它们设置为测试字符串

I have another solution for you, I hope it is useful. 我有另一种解决方案,希望对您有用。

for key in D:
    D[key] +=1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM