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

How to reverse values of keys in dictionary?

So i have this dict:

role_positions = {role1: 1, role2: 2, role3: 3}

How do i reverse the values of it? like this:

role_positions = {role1: 3, role2: 2, role3: 1}

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

>Solution :

You can get values as a list then reversed them and zip with keys and return dict like below:

# python_version > 3.8
>>> dict(zip(role_positions, reversed(role_positions.values())))
{'role1': 3, 'role2': 2, 'role3': 1}

# python_version < 3.8
>>> dict(zip(role_positions, reversed(list(role_positions.values()))))

For older versions of python, for sure about the order of different run-time we need to get the inputted dict as OrderedDict: (here we can read a good explanation)

We suppose we get OrderDict as input, below code is only used for creating OrderDict. if we use the below code in the older version maybe we get a different OrderedDict (because role_positions maybe get a different order) but we suppose the user input OrderDict

from collections import OrderedDict
# we supoose we input below dict
o_dct = OrderedDict((k, v) for k,v in role_positions.items())
dict(zip(o_dct, reversed(list(o_dct.values()))))
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