Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting list into dictionary with index as key [duplicate]

Tags:

python

To convert a list into a dictionary with key as the index of the element and values as the value in the list. i have tried to create it but was facing errors.below is my current code

for each in list:
    dict[each] = list[each]

what is wrong in my code. i am a beginner in python.

like image 868
justin mooc Avatar asked Dec 03 '22 11:12

justin mooc


1 Answers

Try using enumerate! It's nifty:

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

print(dict(enumerate(list))) # >>> {0: 'a', 1: 'b', 2: 'c'}

what is wrong with your code is that you are taking two elements of a list (by subscripting them with the list[value] syntax) and setting them equal to each other.

What you meant to do:

   d = {}
    l = ['a','b','c']
    for k,v in enumerate(l):
        d[k] = v

What this does:

Enumerating a sequence gives you a tuple where an integer is paired with the value of the sequence.Like in my list above, the enumerate(list) itself would be:

for k in enumerate([1,2,3]):
print(k)

Result: (0, 1) (1, 2) (2, 3)

The k and v in the loop first for loop I wrote unpacks the tuples (k= the index 0 of the tuple, v = the second), and the predefined dict (d in my case) sets the enumerate value (d[k], the key) to the value k (the second value of the tuple after enumeration)

Hope this makes sense!

like image 118
Aaron Brandhagen Avatar answered May 05 '23 01:05

Aaron Brandhagen