I am trying to write a function replace(d, v, e)
where d
is a dict
and v
and e
are int
s. 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?