Reverse key value pairing in python dictionary
List instead of a dict
Assuming that your keys are always the integers from 1 to N, it seems that your dict should actually be a list. And whatever you use, you shouldn't use dict
as a variable name.
You would not lose any information with a list:
d = {1: ('a', 'b'), 3: ('e', 'f'), 2: ('c', 'd')}
l = [v for k, v in sorted(d.items())]
# [('a', 'b'), ('c', 'd'), ('e', 'f')]
You also wouldn't lose any information by shifting the indices by -1.
Getting the information back
You have the sorted values directly inside
l
.If you need the keys, you can simply call:
range(len(l))
# range(0, 3)
- If you want the index
i
, you can calll[i]
.
l[1] # Indices have been shifted. 2 is now 1
# ('c', 'd')
- If you want the original dict, you can call:
>>> dict(enumerate(l))
{0: ('a', 'b'), 1: ('c', 'd'), 2: ('e', 'f')}
>>> dict(enumerate(l, 1))
{1: ('a', 'b'), 2: ('c', 'd'), 3: ('e', 'f')}
- In order to get the reversed values, you can simply reverse the list:
>>> l[::-1]
[('e', 'f'), ('c', 'd'), ('a', 'b')]
>>> l[::-1][0]
('e', 'f')
And, in order to answer your original question, if you really want to keep the proposed data format, you can call:
>>> dict(list(enumerate(l[::-1])))
{0: ('e', 'f'), 1: ('c', 'd'), 2: ('a', 'b')}
>>> dict(list(enumerate(l[::-1], 1)))
{1: ('e', 'f'), 2: ('c', 'd'), 3: ('a', 'b')}
You just need:
new_dict = dict(zip(old_dict, reversed(old_dict.values())))
Note, prior to Python 3.8, where dict_values objects are not reversible, you will need something like:
new_dict = dict(zip(old_dict, reversed(list(old_dict.values()))))