'Pythonic way to create a dictionary from array based index values

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 1:[1]

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

Solution 2:[2]

nums = [1,2,3,4,5,6]
my_dict = dict(zip(nums,list(range(len(nums)))))
print(my_dict)

output :

{1: 0, 2: 1, 3: 2, 4: 3, 5: 4, 6: 5}

  • len : get the length of list
  • range: create a series of numbers from 0 to length, length not included
  • list : typecast the range into list
  • zip: combine the two lists
  • dict : typecast the combination into dictionary

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mozway
Solution 2