-2

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?

dmoses
  • 37
  • 1
  • 4
  • 1
    what do you want the end result to be? – Tom McLean Sep 13 '22 at 20:19
  • I would like the end result to be a list of all the start times and a list of all the end times. So far I can get both start and end times using dict.items() but I don't know how to access just start times. I tried val[0] as start is the first item but that did not work either. – dmoses Sep 13 '22 at 20:25
  • 1
    List comprehension example: `[d['start'] for dl in mylist for d in dl]` – jarmod Sep 13 '22 at 20:26
  • 1
    Thanks, I really need to get comfortable with list comprehension this is much simpler than how I was going about it. – dmoses Sep 13 '22 at 20:30
  • For learning, I recommend [Writing Your First List Comprehension](https://realpython.com/lessons/writing-your-first-list-comprehension/) and their [other videos on list comprehension](https://www.google.com/search?q=realpython+list+comprehension). – jarmod Sep 13 '22 at 20:47
  • If the list is flattened (either into an explicit list ahead of time, or implicitly as part of a comprehension, or by using a generator) then we simply get the appropriate key from each dict in the flattened iterable - which is what a comprehension is for. Please see the linked duplicates in order to understand the fundamental techniques. – Karl Knechtel Sep 18 '22 at 09:00

1 Answers1

-1

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]
jarmod
  • 71,565
  • 16
  • 115
  • 122