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

WBOY
Release: 2024-02-09 20:20:05
forward
685 people have browsed it

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

Question content

Suppose I have this dictionary.

mydict = {"abc":[1, 2, 3], "def":[4, 5, 6], "ghi":[7, 8, 9]}
Copy after login

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]}
Copy after login

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]
Copy after login


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
Copy after login

mydict then:

{'abc': [2, 2, 3], 'def': [5, 5, 6], 'ghi': [8, 8, 9]}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!