In Python, how to iterate a dict
and increment values of each key?
D = {k1:1, k2:2}
I want D
to be {k1:2, k2:3}
.
You can use a dict
comprehension to increment each value, then assign it back
>>> {k: v+1 for k,v in D.items()}
{'k1': 2, 'k2': 3}
You can either modify (also called "mutate") the dictionary 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 = { 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 = {"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
I have another solution for you, I hope it is useful.
for key in D:
D[key] +=1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.