问题
I have a dicionary that is initialized like so:
tab = {'Mike': 0, 'Chad': 15, 'Taylor': 2}
I want to be able to add integers to each value in the dictionary.
For example, after adding 5, the dictionary should look like this:
{'Mike': 5, 'Chad': 20, 'Taylor': 7}
It seems as if this can be done with a couple of lines of code but I can't figure it out. I've tried a for loop:
for k in tab.itervalues():
k = k + 5
I run this code and then print out the dictionary:
tab = {'Mike': 0, 'Chad': 15, 'Taylor': 2}
The dictionary has undergone no change. I'm not sure if Python recognizes the values as strings or integers.
回答1:
The easiest way?
for k in tab.keys():
tab[k] += 5
回答2:
tab.itervalues() creates an iterator over values.
You iterate over these, and are handed each value in turn. The values are ints. In Python, these are immutable.
In Python, the statement a += 3 is translated - in most cases - to a = a + 3. a + 3 creates a new int object, for the case where a already referred to an int, and then the name a is rebound to the new object.
So you alter the iteration variable (by rebinding it), but not the value in the map (because it is immutable).
waffle paradox's solution gets around this by using an iterator over keys to access and then rebind the values inside the dict. This is simple and Pythonic and fine.
Alternately, you can embrace immutability, and apply the functional programming paradigm. We want to create a dictionary that is like the one we have but with the keys incremented; and causing tab to refer to this new dictionary is only incidental.
Thus:
tab = dict((k, v + 5) for (k, v) in tab.iteritems())
This approach will often make your life easier when you have a harder problem based on the same fundamental issue.
来源:https://stackoverflow.com/questions/6852819/modifying-dictionary-values-while-iterating-with-dict-values-or-dict-itervalue