1

I am trying to write a function replace(d, v, e) where d is a dict and v and e are ints. The function is supposed to replace all dictionary values of v to e.

This code works fine:

def replace(d, v, e):
    for key, value in d.items():
        if value == v:
            d[key] = e
    return d 

print(replace({1:2, 3:4, 4:2}, 2, 7)) # output: {1: 7, 3: 4, 4: 7}

But when I alter the code to change the value using d.values(), it doesn't work:

def replace(d, v, e):
    for i in d.values():
        if i == v:
            i = e
    return d 
    
print(replace({1:2, 3:4, 4:2}, 2, 7)) # output: {1: 2, 3: 4, 4: 2}

May I have any advice on how to modify the 2nd code to make it work like the 1st code?

Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
  • 7
    You can't. The assignment to `i` only changes the symbol `i` it doesn't effect the dictionary. Stick to the first version. – rdas Jun 03 '22 at 13:14

1 Answers1

1

Modifying the second code "to work" would require using items in place of values, so in short, you cannot modify the value without knowing the key. What your second code does is only to assign the value to i locally in the function without ever affecting the dictionary.

Another remark, your first version of the function modifies the dictionary in place and returns it, which is not a really good practice, you should do either the one or the other.

Finally, here is a version to return a new dictionary without changing the input, using a dictionary comprehension:

def replace(d, v, e):
    return {k: e if val==v else val for k,val in d.items()}

replace({1: 2, 3: 4, 4: 2}, 2, 7)
# {1: 7, 3: 4, 4: 7}
mozway
  • 194,879
  • 13
  • 39
  • 75