Home >Backend Development >Python Tutorial >Use for loop on dictionary to change/update first value using index
Suppose I have this dictionary.
mydict = {"abc":[1, 2, 3], "def":[4, 5, 6], "ghi":[7, 8, 9]}
I can't understand how to use a for loop to update only the first number by 1 in this case. So essentially the result is:
mydict = {"abc":[2, 2, 3], "def":[5, 5, 6], "ghi":[8, 8, 9]}
Searching online I can't seem to find how to do this using index and 1. The only thing I've found is if one knows how to replace the values, or knows if the keys are written down like this:
mydict["abc"] = [2, 2, 3]
You don't need to modify the dictionary, just the lists (its values) contained within it.
for nums in mydict.values(): nums[0] += 1
mydict
then:
{'abc': [2, 2, 3], 'def': [5, 5, 6], 'ghi': [8, 8, 9]}
Lists are mutable, which means they can be modified but not replaced (as opposed to tuples).
The above is the detailed content of Use for loop on dictionary to change/update first value using index. For more information, please follow other related articles on the PHP Chinese website!