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)]}
CodePudding user response:
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)]}
CodePudding user response:
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)}