简体   繁体   中英

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}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM