Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading