Reverse the order of elements in a dictionary

Viewed 310

If I have a dictionary dict1 = {1:'a', 2:'c', 'd':'gh'} and I want to reverse it so that dict2 = {'d':'gh', 2:'c', 1:'a'}. I do not want to change the maping of the dictionary.

I an doing this in python 3.7, which preserves element order in dictionaries. Is there a function that would do this or what code would allow me to do this.

2 Answers

you can convert to a list dict1.items then use the built-in function reversed:

dict(reversed(list(dict1.items())))

output:

{'d': 'gh', 2: 'c', 1: 'a'}

You can use reversed() to reverse the dictionary:

>>> dict1 = {1:'a', 2:'c', 'd':'gh'}
>>> dict2 = dict(reversed(dict1.items()))
>>> dict2
{'d': 'gh', 2: 'c', 1: 'a'}

As @kederrac helpfully pointed out in the comments, the above won't work in Python 3.7, only 3.8. It will trigger a TypeError: 'dict_items' object is not reversible exception. To fix this you will need to cast list() to dict1.items(), as shown in @kederrac's answer. Its probably safe to do this for safer, portable code anyways.

Related