简体   繁体   中英

Getting the item with the maximum value in list of dicts after grouping the dict by key

I have a list of dicts that looks like this:

[{'apples': 99}, {'bananas': '556685'}, {'apples': 88}, {'apples': '2345566'}]

I would like to group the items by the key and return the key of the item with the highest value? ie sum up the values all the apples and sum up the values of all the bananas ad return the higher one — apple or banana I can't seem to figure out a good way of doing this and I'm trying to avoid using a bunch of loops and counter variables.

(Just out of curiosity, is this possible as a one-liner? if so, how?)

After changing all your values to integers:

import itertools as it

a = [{'apples': 99}, {'bananas': 556685}, {'apples': 88}, {'apples': 2345566}]


max((sum(i.values()[0] for i in v), k) for k,v in it.groupby(sorted(a), key=lambda x: x.keys()[0]))[1]

# 'apples'

If you remove the trailing [1] , it will give you even the sum:

# (2345753, 'apples')

Not exactly a one-liner, but I like to use collections.Counter for this kind of tasks because I find it quite readable:

from collections import Counter
from itertools import chain
from operator import itemgetter

a = [{'apples': 99}, {'bananas': 556685}, {'apples': 88}, {'apples': 2345566}]
c = Counter()
for k, v in chain.from_iterable([d.items() for d in a]):
    c[k] += v

print max(c.items(), key=itemgetter(1))[0]

Try this:

reduce(lambda m,n:m if int(m[1])>=int(n[1]) else n,map(lambda p:p.items()[0],a))

I guess it doesn't sort but gives you the highest one in a line.

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