Working on a list of dictionnaries

This practical case applies the basics of using lists, dictionaries, and for loops.

We begin with a list of dictionaries where each dictionary contains text and a timestamp :

my_list =[{'text': 'right now,', 'start': 7.48}, 
{'text': 'on October the 25th', 'start': 10.519},
{'text': 'trees shed their leaves', 'start': 11.1},
{'text': 'and it is a great day', 'start': 14.2},
{'text': 'to write some code', 'start': 15.0}
]
How to concatenate all texts where the timestamps fall between a start time 10 and an end time 14.5 ?

long_text = ''
for dictionnary in my_list:
        if 10 < dictionnary['start'] < 14.5:
            text = dictionnary['text']
            long_text += text + ' '      
print(long_text)

# output :
'on October the 24th trees shed their leaves and it is a great day'

By using list comprehensions, this code can be made more concise:

long_text2 = ' '.join([dictionnary['text'] for dictionnary in my_list if 10 < dictionnary ['start'] < 14.5])'
print(long_text2)

see more articles