I have a dictionary where keys are strings, and values are integers.
list1 = [{'id': 1, 'ent': 123}, {'id': 2, 'ent': 123}, {'id': 3, 'ent': 456}, {'id': 4, 'ent': 456}, {'id': 5, 'ent': 123}]
How do I get the dictionary with the maximum value of id
for given ent
?
Expected Outcome:
[{'id': 4, 'ent': 456},{'id': 5, 'ent': 123}]
CodePudding user response:
Code:
[{'id': max(list(filter(None,[v['id'] if v['ent'] == i else None for v in list1]))), 'ent':i} for i in set([i['ent'] for i in list1])]
Output:
[{'id': 4, 'ent': 456}, {'id': 5, 'ent': 123}]
CodePudding user response:
res = {}
for item in list1:
id, ent = item['id'], item['ent']
try:
if id > res[ent]:
res[ent] = id
except KeyError:
res[ent] = id
CodePudding user response:
- First filter on
'ent'
. You can use a set comprehension{d['ent'] for d in list1}
- Then use
max
with a key function to find that max of that filtered list withmax([d for d in list1 if d['ent']==e], key=lambda d: d['id'])
So:
for e in {d['ent'] for d in list1}:
print(max([d for d in list1 if d['ent']==e], key=lambda d: d['id']))
Prints:
{'id': 4, 'ent': 456}
{'id': 5, 'ent': 123}
Which can be a list comprehension:
[max([d for d in list1 if d['ent']==e], key=lambda d: d['id'])
for e in {d['ent'] for d in list1}]
Result:
[{'id': 4, 'ent': 456}, {'id': 5, 'ent': 123}]
You can also use a sort approach that uniquifies the list based on the sorted result:
list({d['ent']:d
for d in sorted(list1, key=lambda d: (d['id'], d['ent']))}.values())
That is potentially faster with large lists since it is O(n log n)
complexity versus the O(n * n)
of the other approaches.