Home > Software design >  convert a list to dictionary by using formkeys with different values
convert a list to dictionary by using formkeys with different values

Time:10-07

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.

CodePudding user response:

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

dict = {a: b for b,a in enumerate(lst)}

CodePudding user response:

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

CodePudding user response:

{y:x for x,y in enumerate(['a', 'b', 'c', 'd', 'e'])}

CodePudding user response:

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}
  • Related