简体   繁体   English

如果值是另一个键的名称,如何将键的值更改为另一个键的值?

[英]How do I change a key's value to that of another key's value if the value is the name of another key?

To explain what I mean, I'm adding keys and values to a dictionary but if a key in the dictionary has a value that's the name of another key, I want that key to be assigned the other key's value.为了解释我的意思,我将键和值添加到字典中,但是如果字典中的键的值是另一个键的名称,我希望为该键分配另一个键的值。 For example, if I have dict1 = {"a": 100, "b": 200, "c": "a"} is it possible to change the value of c to 100 (which is a's value)?例如,如果我有dict1 = {"a": 100, "b": 200, "c": "a"}是否可以将 c 的值更改为 100(这是 a 的值)? So instead it would be dict1 = {"a": 100, "b": 200, "c": 100} The code I have right now is obviously wrong and giving me an error but I was trying to type out what I thought would work所以改为dict1 = {"a": 100, "b": 200, "c": 100}我现在拥有的代码显然是错误的,并且给了我一个错误,但我试图输入我的想法会工作

for x, y in dict1.items():
       if dict1[x] == dict1[x]:
           dict1[x] = dict1[y]
       print(x, y)

You can use:您可以使用:

my_dict = {"a": 100, "b": 200, "c": "a"}
for k, v in my_dict.items():
    if v in my_dict:
        my_dict[k] = my_dict[v]

You can alternatively use a dict comprehension:您也可以使用 dict 理解:

result = {
    k: my_dict[v] if v in my_dict else v
    for k, v in my_dict.items()
}

Output:输出:

{'a': 100, 'b': 200, 'c': 100}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM