Search code examples
pythondictionarynested-lists

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?


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]