I have a txt file with some lists that contain dictionaries. This is how it looks:
[]
[]
[{'userId': '61f6b0e2-XXXX-XXXX-XXXX-82440f1b316b', 'lastLogOnDateTime': '2022-04-11T08:11:30.077Z'}]
[{'userId': 'a159ace2-XXXX-XXXX-XXXX-221885ce1282', 'lastLogOnDateTime': '2022-03-01T15:31:42.661Z'}]
[{'userId': '5e2a0b81-XXXX-XXXX-XXXX-4e7ac8d1c0d1', 'lastLogOnDateTime': '2022-04-14T08:25:11.354Z'}]
[{'userId': '75bfd26a-XXXX-XXXX-XXXX-52238cf882ab', 'lastLogOnDateTime': '2022-04-14T10:22:16.466Z'}]
[{'userId': 'ecff3ce3-XXXX-XXXX-XXXX-21a9baa658de', 'lastLogOnDateTime': '2022-01-19T16:00:24.838Z'}]
[{'userId': '5983f74c-XXXX-XXXX-XXXX-6c565edd08cc', 'lastLogOnDateTime': '2022-03-21T12:56:45.099Z'}, {'userId': '865e5246-XXXX-XXXX-XXXX-ef19a8ae4ce7', 'lastLogOnDateTime': '2022-04-14T09:10:07.863Z'}]
[{'userId': '7b2d3af3-XXXX-XXXX-XXXX-8870c5f19287', 'lastLogOnDateTime': '2022-04-14T06:06:38.75Z'}]
[{'userId': 'ecff3ce3-XXXX-XXXX-XXXX-21a9baa658de', 'lastLogOnDateTime': '2022-03-15T12:45:39.116Z'}, {'userId': '6560f0cd-XXXX-XXXX-XXXX-ca0b743734bb', 'lastLogOnDateTime': '2022-04-07T05:04:38.345Z'}, {'userId': '5865d24c-XXXX-XXXX-XXXX-57286e4aeac9', 'lastLogOnDateTime': '2022-04-14T06:54:56.632Z'}]
[{'userId': 'e7b36f37-XXXX-XXXX-XXXX-f6a3b2bff570', 'lastLogOnDateTime': '2021-10-29T14:29:20.445Z'}, {'userId': '5983f74c-XXXX-XXXX-XXXX-6c565edd08cc', 'lastLogOnDateTime': '2021-11-23T12:25:31.788Z'}]
[{'userId': '79a60545-XXXX-XXXX-XXXX-23374487c8e5', 'lastLogOnDateTime': '2022-04-14T09:09:36.33Z'}]
[{'userId': '865e5246-XXXX-XXXX-XXXX-ef19a8ae4ce7', 'lastLogOnDateTime': '2022-03-22T07:36:12.719Z'}]
[{'userId': 'e7b36f37-XXXX-XXXX-XXXX-f6a3b2bff570', 'lastLogOnDateTime': '2021-10-27T08:05:54.091Z'}, {'userId': 'b3169036-XXXX-XXXX-XXXX-50f7c4806fa3', 'lastLogOnDateTime': '2021-11-05T11:01:39.796Z'}]
[{'userId': '5983f74c-XXXX-XXXX-XXXX-6c565edd08cc', 'lastLogOnDateTime': '2021-12-17T14:06:03.918Z'}]
so as you can see some lists are empty whereas others contain multiple dictionaries. What I can't figure out is how to iterate over a list and then check the dictionaries for the dictionary with the most recent DateTime. So each list should only contain one dictionary and this is the dictionary that has the most recent DateTime.
for example:
[{'userId': '5983f74c-XXXX-XXXX-XXXX-6c565edd08cc', 'lastLogOnDateTime': '2022-03-21T12:56:45.099Z'}, {'userId': '865e5246-XXXX-XXXX-XXXX-ef19a8ae4ce7', 'lastLogOnDateTime': '2022-04-14T09:10:07.863Z'}]
should become:
[{'userId': '865e5246-XXXX-XXXX-XXXX-ef19a8ae4ce7', 'lastLogOnDateTime': '2022-04-14T09:10:07.863Z'}]
Ofcourse the empy ones may remain empty.
Thanks!
CodePudding user response:
You can sort the list in descending order based on the lastLogOnDateTime
field and just take the first dictionary of the list
res = []
s = sorted(list_of_dict, key=lambda d: d['lastLogOnDateTime'], reverse=True)
if len(s)>0:
res = [s[0]]