Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Switching keys of a dictionary without switching the values

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading