convert a list to dictionary by using formkeys with different values

Question:

can I have a list that I use formkeys to convert it into a dictionary and the values of the dictionary be their indexes of the list?

for example my list is ["a", "b", "c", "d", "e"]

and if I use formkeys, I want it will be {"a" :0 , "b" :1 , "c" :2 , "d" :3 , "e" :4 }

could you tell me how can I do it?

or if you know another way that it’s order is less than this way (in python), please tell me.

Asked By: N Th

||

Answers:

Suppose lst = ['a', 'b', 'c' ...]:

dict = {a: b for b,a in enumerate(lst)}
Answered By: Colonel Mustard

The dict.fromkeys method is meant to assign the same value to each of the key in a given sequence, which is not the case if you want a differing index as a value for each key.

Instead, you can enumerate the list and reverse the generated index-value tuples to construct a new dict:

dict(map(reversed, enumerate(lst)))

Demo: https://replit.com/@blhsing/MiserableOrdinaryEmulator

Answered By: blhsing
{y:x for x,y in enumerate(['a', 'b', 'c', 'd', 'e'])}
Answered By: Amandeep Singh

You can also achieve this by using itertools.count() along with zip() as:

>>> from itertools import count
>>> lst = ["a", "b", "c", "d", "e"]

>>> dict(zip(lst,count()))
{'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4}

You can also use range() to skip the import of itertools library. For example:

>>> dict(zip(lst,range(len(lst))))
{'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4}
Answered By: Moinuddin Quadri
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.