简体   繁体   中英

Finding and replacing a value in a Python dictionary

I'm a complete newbie to stackoverflow, so please excuse me if I end up posting this in the wrong place (or any other newbie-related mitakes! Thanks!).

My question pertains to Python 3.x, where I am trying to basically access a value in a very small dictionary (3 keys, 1 value each). I have searched high and low on the web (and on here), but cannot seem to find anything pertaining to replacing a value in a dictionary. I have found the "replace" function, but does not seem to work for dictionaries.

So, here is my dictionary:

a1 = {"Green": "Tree", "Red": "Rose", "Yellow": "Sunflower"}

How would I go about querying the value "Rose" to replace it with "Tulip," for example?

Any help would be greatly appreciated, even if it is just to point me in the right direction!

Thanks so much!

You first must find the key that has the value "Rose" :

for color, flower in a1.items():
    if flower == "Rose":
        a1[color] = "Tulip"

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM