简体   繁体   English

按键将字典分组后,获取字典列表中具有最大值的项目

[英]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: 如果删除结尾的[1] ,它甚至会给您总和:

# (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: 不完全是单线的,但是我喜欢使用collections.Counter来完成这类任务,因为我发现它很可读:

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. 我猜它不会排序,但是会为您提供最高的一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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