From Python: create dict from list and auto-gen/increment the keys (list is the actual key values)?, it's possible to create a dict
from a list
using enumerate
to generate tuples made up of incremental keys and elements in life, i.e.:
>>> x = ['a', 'b', 'c']
>>> list(enumerate(x))
[(0, 'a'), (1, 'b'), (2, 'c')]
>>> dict(enumerate(x))
{0: 'a', 1: 'b', 2: 'c'}
It is also possible to reverse the key-value by iterating through every key in the dict
(assuming that there is a one-to-one mapping between key-value pairs:
>>> x = ['a', 'b', 'c']
>>> d = dict(enumerate(x))
>>> {v:k for k,v in d.items()}
{'a': 0, 'c': 2, 'b': 1}
Given the input list ['a', 'b', 'c']
, how can achieve the dictionary where the elements as the key and incremental index as values without trying to loop an additional time to reverse the dictionary?