Finding and replacing a value in a Python dictionary

11,410

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

for color, flower in a1.items():
    if flower == "Rose":
        a1[color] = "Tulip"
Share:
11,410
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    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!