Switching keys of a dictionary without switching the values
Question:
Let’s say I have a dictionary like below
myDict = {"a": 1, "b": 2, "c": 3, "d": 4}
and I’m trying to get this result
myDict = {"b": 1, "a": 2, "c": 3, "d": 4}
I tried running using
dictionary[new_key] = dictionary.pop(old_key)
But thats just deleting and appending a new key and value to the dictionary. It would result in:
myDict = {"b": 2, "c": 3, "d": 4, "a": 2}
Thanks in advance for the answer
Answers:
So I understand you aim to preserve the sequence.
Make first a new dictionary that maps the old keys to the new keys:
mapping = {"a": "b", "b": "a"}
Now you can generate the new structure
my_dict = {mapping.get(key, key): value for key, value in my_dict.items()}
The get
method here tries to map the key, but uses the key itself, if the key is not in the mapping.
Let’s say I have a dictionary like below
myDict = {"a": 1, "b": 2, "c": 3, "d": 4}
and I’m trying to get this result
myDict = {"b": 1, "a": 2, "c": 3, "d": 4}
I tried running using
dictionary[new_key] = dictionary.pop(old_key)
But thats just deleting and appending a new key and value to the dictionary. It would result in:
myDict = {"b": 2, "c": 3, "d": 4, "a": 2}
Thanks in advance for the answer
So I understand you aim to preserve the sequence.
Make first a new dictionary that maps the old keys to the new keys:
mapping = {"a": "b", "b": "a"}
Now you can generate the new structure
my_dict = {mapping.get(key, key): value for key, value in my_dict.items()}
The get
method here tries to map the key, but uses the key itself, if the key is not in the mapping.