I have list of dictionary below
rec=[{
'Name': 'aRe',
'Email': 'huul@gmail.com',
'timestamp': '2021-11-29T04:33:28.138522Z'
},
{
'Name': 'Umar',
'Email': 'chdtn@gmail.com',
'timestamp': '2021-11-28T04:33:28.138522Z'
},
{
'Name': 'Are',
'Email': 'ddhit@gmail.com',
'timestamp': '2021-11-27T04:33:28.138522Z'
},
{
'Name': 'arE',
'Email': 'deyan@gmail.com',
'timestamp': '2021-11-28T06:59:58.975864Z'
},
{
'Name': 'umaR',
'Email': 'ddhi@gmail.com',
'timestamp': '2021-11-29T04:33:28.138522Z'
},
{
'Name': 'Sc',
'Email': 'deyan@gmail.com',
'timestamp': '2022-02-01T15:02:12.301701Z'
}
]
- if duplicate id is present then extract the dict with latest timestamp
Expected out
[{'Name': 'umaR',
'Email': 'ddhi@gmail.com',
'timestamp': '2021-11-29T04:33:28.138522Z'},
{'Name': 'aRe',
'Email': 'huul@gmail.com',
'timestamp': '2021-11-29T04:33:28.138522Z'},
{'Name': 'Sc',
'Email': 'deyan@gmail.com',
'timestamp': '2022-02-01T15:02:12.301701Z'}]
Code is below
from itertools import groupby
filtered_recs = []
for key, group_iter in groupby(recs, lambda rec: rec['Name'].lower()):
recent_rec = max(group_iter, key = lambda rec: rec['timestamp'])
filtered_recs.append(recent_rec)
filtered_recs
My code is working fine if all the 'Name' in same case. Like name are like, 'are', 'umar', 'sc' not for irregular case letters