简体   繁体   中英

Getting key with maximum value in dictionary for each Key value

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}]

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}]
res = {}
for item in list1:
    id, ent = item['id'], item['ent']
    try:
        if id > res[ent]:
            res[ent] = id
    except KeyError:
        res[ent] = id
  1. First filter on 'ent' . You can use a set comprehension {d['ent'] for d in list1}
  2. Then use max with a key function to find that max of that filtered list with max([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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM