How to Reverse Python Dictionary

By | 2018-07-02

From time to time I need to create a dictionary from the given list. The easiest and pythonic way to do it is to use enumerate() function and dictionary comprehensions.

Original list:

>>> orig_list = ['song1', 'song2', 'song3', 'song4']

Desired outcome:

>>> {'song1': 0, 'song2': 1, 'song3': 2, 'song4': 3}

The dictionary keys are elements of the original list and values are positions of the elements in the list. To achieve the final result we use a dict comprehensions described in PEP274.

>>> orig_list = ['song1', 'song2', 'song3', 'song4']
>>> out_dict = {f: i for i, f in enumerate(orig_list)}
>>> out_dict
{'song1': 0, 'song2': 1, 'song3': 2, 'song4': 3}

Happy coding!