How to enumerate keys from list and get values without hardcoding keys?

Question:

How to enumerate keys from list and get values without hard coding keys? my_list contains tuples and I am trying to generate dictionary based on the position of the tuple in list. num in enumerate gives number like 0, 1,2, …etc.

my_list = [(1,2),(2,3),(4,5),(8,12)]
my_list

di = {'0':[],'1':[]} #manually - how to automate with out specifying keys from enumarate function?
for num,i in enumerate(my_list):
    di['0'].append(i[0])
    di['1'].append(i[0])
print(di) # {'0': [1, 2, 4, 8], '1': [1, 2, 4, 8]}

Output – How do I get this result?

di = {'0':[(1,2)],
      '1':[(2,3)],
      '2':[(4,5)],
      '3':[(8,12)]}
Asked By: sharp

||

Answers:

Is this what you are looking for?

You can use enumerate to get the index of each tuple in the list and then create a dict comprehension.

di = {str(i):[t] for i,t in enumerate(my_list)}
di
{'0': [(1, 2)], 
 '1': [(2, 3)], 
 '2': [(4, 5)], 
 '3': [(8, 12)]}
Answered By: Akshay Sehgal

Just enumerate your way through the list:

my_list = [(1,2),(2,3),(4,5),(8,12)]

di = {str(index):[item] for (index,item) in enumerate(my_list)}
Answered By: quamrana
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.