Home > Mobile >  How to reverse values of keys in dictionary?
How to reverse values of keys in dictionary?

Time:06-19

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}

CodePudding user response:

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()))))
  • Related