Reputation: 15
In the following dictionary, a user can refer to a key as a variable for defining another value:
d = {'a_key': 'a_value', 'b_key': 'a_key+1'}
I have to replace these references by the corresponding values, in order to obtain this desired output:
d = {'a_key': 'a_value', 'b_key': 'a_value+1'}
I thought it would be easy, but this one drives crazy since a few hours. I got to this code:
for k in d.keys():
print("key: " + k)
print("value: " + d[k])
for v in d.values():
print("value_before: " + v)
v = v.replace(k, d[k])
print("value_after: " + v)
print(d)
The output is:
key: a_key
value: a_value
value_before: a_value
value_after: a_value
value_before: a_key+1
value_after: a_value+1
key: b_key
value: a_key+1 # WHY??
value_before: a_value
value_after: a_value
value_before: a_key+1
value_after: a_key+1
{'a_key': 'a_value', 'b_key': 'a_key+1'}
As we see, the first iteration seems to do the job, before it is cancelled by the second one. I just don't unserstand why. I also tried to adapt the very specific answers to that question: Replace values in dict if value of another key within a nested dict is found in value, but to no avail. I'm looking for a general answer to: how to get the desired output?
From a theoretic point of view, I would also like to understand why the "b_value"
is reset to a_key+1
. Thanks.
Upvotes: 0
Views: 542
Reputation: 42143
The problem is that you are modifying temporary variable v
but you are not placing the modified values back in the dictionary.
Try replacing :
for v in d.values():
v = v.replace(k, d[k])
with:
for r,v in d.items():
d[r] = v.replace(k, d[k])
Upvotes: 1