Home > other >  How do I change a key's value to that of another key's value if the value is the name of a
How do I change a key's value to that of another key's value if the value is the name of a

Time:07-18

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)? 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

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

CodePudding user response:

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:

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}
  • Related