Obtener el elemento con el valor máximo en la lista de dictados después de agrupar el dictado por clave

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? i.e. 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?)

preguntado el 01 de febrero de 12 a las 14:02

3 Respuestas

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')

Respondido 01 Feb 12, 18:02

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]

Respondido 01 Feb 12, 18:02

This one has the advantage of being more robust to the dictionaries, i.e. it handles {'apples': 99, 'bananas': 23} as well. - DSM

Nice. You can make it a one-liner: sum(map(Counter, a), Counter()).most_common(1)[0][0] - eumiro

@eumiro Adding counters objects directly it's a very interesting solution. - jcollado

Prueba esto:

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.

Respondido 01 Feb 12, 19:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.