python - 在Python中对dict中的值进行分组和排序

标签 python sorting group-by

我在 python 中有一个字典,如下所示,我必须按“标签”分组并获取每个“标签”的最高“置信度”值

[{'label': 'id',
  'confidence': 0.11110526,
  'topleft': {'x': 0, 'y': 0},
  'bottomright': {'x': 187, 'y': 57}},

{'label': 'id',
  'confidence': 0.10690566,
  'topleft': {'x': 265, 'y': 0},
  'bottomright': {'x': 525, 'y': 54}},

 {'label': 'name',
  'confidence': 0.15541315,
  'topleft': {'x': 9, 'y': 24},
  'bottomright': {'x': 116, 'y': 58}},

 {'label': 'group',
  'confidence': 0.12578075,
  'topleft': {'x': 53, 'y': 24},
  'bottomright': {'x': 153, 'y': 61}},

 {'label': 'name',
  'confidence': 0.12709439,
  'topleft': {'x': 0, 'y': 0},
  'bottomright': {'x': 247, 'y': 84}},

 {'label': 'group',
  'confidence': 0.116156094,
  'topleft': {'x': 96, 'y': 23},
  'bottomright': {'x': 191, 'y': 61}}]    

如何有效地实现这一目标

最佳答案

您可以使用groupby来做到这一点

for n,g in groupby(tst,key=lambda x:x['label']):
     print n,max(list(g),key=lambda x:x['confidence']).get('confidence')

结果:

id 0.11110526
name 0.15541315
group 0.12578075
name 0.12709439
group 0.116156094

关于python - 在Python中对dict中的值进行分组和排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51056938/

相关文章:

python - 在 groupby 数据框中查找给定日期的最接近日期(Python)

Python 条件求和使用日期和条件

Python:排序函数的参数

c - 参数中的指针出现问题..c 中的冒泡排序

mysql - SQL:如何使用 GROUP BY 来获取聚合的聚合?

python - 对 groupby 中的多索引执行函数

python - tf.nn.l2_loss 和 tf.contrib.layers.l2_regularizer 是否与在 tensorflow 中添加 L2 正则化的目的相同?

Python类: How to check whether an attribute is defined inside __init__ or outside __init__

python - 在 SWIG 编译中 : In header file in interface is unable to resolve other header files.

python - 检查列表是升序还是降序(使用 FOR)