I am in the process of learning Python and, as of right now, this is how I would create a dictionary of the index, value pairs in an array. If I’m not mistaken, this operation would be O(n) time complexity.
Is there a more pythonic way to make this dictionary where the key is the value of the items in the array, and the value is the index? If so, does that more pythonic way decrease time complexity?
nums = [1, 2, 3, 4, 5]
d = {}
for idx, val in enumerate(nums):
d[val] = idx
desired result
{1: 0, 2: 1, 3: 2, 4: 3, 5: 4}
>Solution :
A dictionary comprehension is a quite pythonic variant of your for loop:
nums = [1, 2, 3, 4, 5]
d = {k:v for v,k in enumerate(nums)}
Output: {1: 0, 2: 1, 3: 2, 4: 3, 5: 4}
An alternative could be to use itertools.count:
from itertools import count
d = dict(zip(nums,count()))