用dict值中的相应值替换键引用 [英] Replace key references by corresponding values in dict values
问题描述
在下面的词典中,用户可以将键作为变量来定义另一个值:
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)
输出为:
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?
从理论上讲,我还想了解为什么将"b_value"
重置为 a_key + 1
.谢谢.
From a theoretic point of view, I would also like to understand why the "b_value"
is reset to a_key+1
. Thanks.
推荐答案
问题是您正在修改临时变量 v
,但没有将修改后的值放回字典中.
The problem is that you are modifying temporary variable v
but you are not placing the modified values back in the dictionary.
尝试替换:
for v in d.values():
v = v.replace(k, d[k])
具有:
for r,v in d.items():
d[r] = v.replace(k, d[k])
这篇关于用dict值中的相应值替换键引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!