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 access item in a nested list of dictionaries python?

I have the following format saved to a variable:

[[{'start': 88608, 'end': 94176}], [{'start': 56352, 'end': 63456}, {'start': 119328, 'end': 151008}], [{'start': 88608, 'end': 114144}, {'start': 123936, 'end': 131040}, {'start': 136224, 'end': 160000}], [{'start': 79392, 'end': 144864}], [{'start': 110112, 'end': 147936}]]

How would I go about getting the values attached to start and end labels? For example, how would I get 88608, 56352, 119328 into their own list?

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 :

You can use a simple list comprehension to iterate over the contents of your list of list of dict. For example:

my_list= [[{'start': 88608, 'end': 94176}], [{'start': 56352, 'end': 63456}, {'start': 119328, 'end': 151008}], [{'start': 88608, 'end': 114144}, {'start': 123936, 'end': 131040}, {'start': 136224, 'end': 160000}], [{'start': 79392, 'end': 144864}], [{'start': 110112, 'end': 147936}]]

start_list = [d['start'] for dl in my_list for d in dl]
end_list = [d['end'] for dl in my_list for d in dl]

Results are:

start_list = [88608, 56352, 119328, 88608, 123936, 136224, 79392, 110112]
end_list = [94176, 63456, 151008, 114144, 131040, 160000, 144864, 147936]
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