q-compute
q-compute

Reputation: 651

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!

Upvotes: 4

Views: 14201

Answers (4)

Punith Raj
Punith Raj

Reputation: 1

I think the below code should help.

my_list = ['A', 'B', 'C', 'D']
my_index = []
my_dict = {}

for i in range(len(my_list)): 
    my_index.append(i+1)

for key in my_index: 
    for value in my_list: 
        my_dict[key] = value

Upvotes: 0

Aaditya Ura
Aaditya Ura

Reputation: 12669

By default enumerate start from 0 , but you can set by this value by second argument which is start , You can add +1 to every iterator if you want to start from 1 instead of zero :

print({index+1:value for index,value in enumerate(lst)})

output:

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

Above dict comprehension is same as :

dict_1={}
for index,value in enumerate(lst):
    dict_1[index+1]=value
print(dict_1)

Upvotes: 1

Vinay Singh
Vinay Singh

Reputation: 21

Using Dict Comprehension and enumerate

print({x:y for x,y in enumerate(lst,1)})

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

Using Dict Comprehension , zip and range-

print({x:y for x,y in zip(range(1,len(lst)+1),lst)})

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

Upvotes: 0

Patrick Haugh
Patrick Haugh

Reputation: 60974

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

Upvotes: 14

Related Questions