Home  >  Article  >  Backend Development  >  Use for loop on dictionary to change/update first value using index

Use for loop on dictionary to change/update first value using index

WBOY
WBOYforward
2024-02-09 20:20:05689browse

在字典上使用 for 循环来使用索引更改/更新第一个值

Question content

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]

Correct answer


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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete