Use a dictionary comprehension to build a new dictionary, so you can replace the keys in one go:
result = {key.replace('%', ' '): value for key, value in result.items()}
The comprehension consists of:
- an expression to generate a key, the part before the
:
- an expression to generate a value, the part after
:
but before the for
- a
for
loop; you'll get as many key-value
pairs as the for
loop iterates (unless you add more for
loops or if
filters).
Your own solution didn't work, because str.replace()
creates a new string object and returns that. The old string is never changed, because strings are immutable; they can't be altered in-place. If you wanted to do the work in a loop, you'd have to:
- store the result of the
str.replace()
operation.
- remove the old key (storing the value that it referenced temporarily)
- add the new key to the dictionary, making it point to the value for the old key.
However, looping over a dictionary while mutating it (deleting and adding keys is mutating), is not safe and thus not supported. You'd have to loop over a copy of the keys; create one with list(result)
:
for key in list(result):
if '%' in key:
new_key = key.replace('%', ' ')
value = result.pop(key) # remove the old key, store the value
result[new_key] = value
Re-generating the dictionary with a dictionary comprehension is just easier, at this point.
Note that in both approaches, you can end up with fewer keys if replacing '%'
with ' '
leads to collisions! Which value remains after processing depends on which now-duplicate key was processed last.