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
x
5
1
for x, y in dict1.items():
2
if dict1[x] == dict1[x]:
3
dict1[x] = dict1[y]
4
print(x, y)
5
Advertisement
Answer
You can use:
JavaScript
1
5
1
my_dict = {"a": 100, "b": 200, "c": "a"}
2
for k, v in my_dict.items():
3
if v in my_dict:
4
my_dict[k] = my_dict[v]
5
You can alternatively use a dict comprehension:
JavaScript
1
5
1
result = {
2
k: my_dict[v] if v in my_dict else v
3
for k, v in my_dict.items()
4
}
5
Output:
JavaScript
1
2
1
{'a': 100, 'b': 200, 'c': 100}
2