I have a list of dictionaries, and would like to split the dictionaries based on the value of key "timestamp"
. The idea is to group dictionaries of semester 1 (January to July) and dictionaries of semester 2 (August to December). How can I do that in a performance-effective manner?
This is my code:
group1 = ['2020-01', '2020-02', '2020-03', '2020-04', '2020-05', '2020-06']
data = [
{
'timestamp': '2020-01-01T00:00:00Z',
'price': 7204.54,
'volume_24h': 13086960135,
'market_cap': 130644686531},
{
'timestamp': '2020-01-01T01:00:00Z',
'price': 7218.55,
'volume_24h': 13133228186,
'market_cap': 130899528700},
{
'timestamp': '2020-01-01T02:00:00Z',
'price': 7241.8,
'volume_24h': 13257849556,
'market_cap': 131321418482
}
]
semester_1 = [i for i in data if group1 in i['timestamp']]
Unfortunately, it throws an error because group1
is a list.
CodePudding user response:
You can try to check if the substring of timestamp including that date is in the list group1:
group1 = [f'2020-0{i}' for i in range(1,7)]
data = [{'timestamp': '2020-01-01T00:00:00Z',
'price': 7204.54,
'volume_24h': 13086960135,
'market_cap': 130644686531},
{'timestamp': '2020-01-01T01:00:00Z',
'price': 7218.55,
'volume_24h': 13133228186,
'market_cap': 130899528700},
{'timestamp': '2020-01-01T02:00:00Z',
'price': 7241.8,
'volume_24h': 13257849556,
'market_cap': 131321418482}]
semester_1 = [item for item in data if item['timestamp'][:7] in group1]
CodePudding user response:
Try:
semester_1 = [i for i in data if i['timestamp'][0:7] in group1]
Or even without defininig group1
:
semester_1 = [i for i in data if int(i['timestamp'][5:7]) < 7]