Skip to content
Advertisement

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

JavaScript

Advertisement

Answer

You can use:

JavaScript

You can alternatively use a dict comprehension:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement