How to access item in a nested list of dictionaries python?

Question:

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?

Asked By: dmoses

||

Answers:

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]
Answered By: jarmod

Somthing like this: (maybe)? tm is your list of things.



starts = [dc['start'] for lst in tm for dc in lst]
ends = [dc['end'] for lst in tm for dc in lst]

Answered By: Daniel Hao
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.