Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Create dictionary with list index number as key and list element as value?

All the questions I've seen do the exact opposite of what I want to do:

Say I have a list:

lst = ['a','b','c']

I am looking to make a dictionary where the key is the element number (starting with 1 instead of 0) and the list element is the value. Like this:

{1:'a', 2:'b', 3:'c'}

But for a long list. I've read a little about enumerate() but everything I've seen has used the list element as the key instead.

I found this:

dict = {tuple(key): idx for idx, key in enumerate(lst)}

But that produces:

{'a':1, 'b':2, 'c':3}

... which is the opposite of what I want. And, also in a weird notation that is confusing to someone new to Python.

Advice is much appreciated! Thanks!

like image 207
q-compute Avatar asked Oct 21 '25 15:10

q-compute


1 Answers

enumerate has a start keyword argument so you can count from whatever number you want. Then just pass that to dict

dict(enumerate(lst, start=1))

You could also write a dictionary comprehension

{index: x for index, x in enumerate(lst, start=1)}
like image 88
Patrick Haugh Avatar answered Oct 23 '25 07:10

Patrick Haugh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!