简体   繁体   中英

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM