Reverse key value pairing in python dictionary

Viewed 1325

I need a way to reverse my key values pairing. Let me illustrate my requirements.


dict = {1: (a, b), 2: (c, d), 3: (e, f)}

I want the above to be converted to the following:

dict = {1: (e, f), 2: (c, d), 3: (a, b)}
5 Answers

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

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 call l[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')}

Try the following

dict_ = {1: ('a','b'), 2: ('c','d'), 3: ('e','f')}
values = [y for x, y in dict_.items()][::-1]
res = {}
for x, y in enumerate(dict_.items()):
    res[y[0]] = values[x]

print(res)

This is the output:

{1: ('e', 'f'), 2: ('c', 'd'), 3: ('a', 'b')}

This should accomplish the desired outcome.

def rev_keys(d: dict) -> dict:
    '''Return dictionary structure with the 
        keys reasigned in opposite order'''
    old_keys = list(d.keys())
    new_keys = old_keys[::-1]
    nd = {}
    for ki in range(len(new_keys)):
        nd[new_keys[ki]]= d[old_keys[ki]]
    return nd

Given and input looking like:

dt = {'1': ('a','b'), '2': ('c','d'), '3': ('e','f')}

rev_keys(dt)

returns:

{'3': ('a', 'b'), '2': ('c', 'd'), '1': ('e', 'f')}

You can zip the original dictionary's keys with the original dictionary's values, and since you want the values to be reversed, you can use the negative striding [::-1].

Note that dict.values() cannot be subscripted, hence you will need to convert it into a list first:

dct = {1: ('a', 'b'), 2: ('c', 'd'), 3: ('e', 'f')}
dct = dict(zip(dct, list(dct.values())[::-1]))
print(dct)

Output:

{1: ('e', 'f'), 2: ('c', 'd'), 3: ('a', 'b')}
Related