Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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()))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading