python在字典列表中修剪字典

时间:2017-04-20 13:43:02

标签: python list dictionary

我有以下列表,其中可以包含多个不同大小的词典。
每个字典中的键都是唯一的,但不同的字典中可能存在一个键。
各个字典的值都是唯一的。

我想减少我的词典,以便它们包含所有词典中值最高的键和值。

例如,键'1258'存在于四个词典中的三个词典中,并且它仅在最后一个词典中具有最高值,因此在重构列表中,此键及其值将在最后一个词典中只要。 如果该密钥在其他字典中不存在,则它将保留在其所属的字典中。 这是样本数据:

[{'1258': 1.0167004,
  '160': 1.5989301000000002,
  '1620': 1.3058813000000002,
  '2571': 0.7914598,
  '26': 4.554409,
  '2943': 0.5072369,
  '2951': 0.4955711,
  '2952': 1.2380746000000002,
  '2953': 1.6159719,
  '2958': 0.4340355,
  '2959': 0.6026906,
  '2978': 0.619001,
  '2985': 1.5677016,
  '3075': 1.04948,
  '3222': 0.9721148000000001,
  '3388': 1.680108,
  '341': 0.8871856,
  '3443': 0.6000103,
  '361': 2.6682623000000003,
  '4': 5.227341,
  '601': 2.2614983999999994,
  '605': 0.6303175999999999,
  '9': 5.0326675},
 {'1457': 5.625237999999999,
  '1469': 25.45585200000001,
  '1470': 25.45585200000001,
  '160': 0.395728,
  '1620': 0.420267,
  '2571': 0.449151,
  '26': 0.278281,
  '601': 0.384822,
  '605': 5.746278700000001,
  '9': 1.487241},
 {'1258': 0.27440200000000003,
  '1457': 0.8723639999999999,
  '1620': 0.182567,
  '2571': 0.197134,
  '2943': 0.3461654,
  '2951': 0.47372800000000004,
  '2952': 0.6662919999999999,
  '2953': 0.6725458,
  '2958': 0.4437159,
  '2959': 0.690856,
  '2985': 0.8106226999999999,
  '3075': 0.352618,
  '3222': 0.7866500000000001,
  '3388': 0.760664,
  '3443': 0.129771,
  '601': 0.345448,
  '605': 1.909823,
  '9': 0.888999},
 {'1258': 1.0853083,
  '160': 0.622579,
  '1620': 0.7419095,
  '2571': 0.9828758,
  '2943': 2.254124,
  '2951': 0.6294688,
  '2952': 1.0965362,
  '2953': 1.8409954000000002,
  '2958': 0.7394122999999999,
  '2959': 0.9398920000000001,
  '2978': 0.672122,
  '2985': 1.2385512999999997,
  '3075': 0.912366,
  '3222': 0.8364904,
  '3388': 0.37316499999999997,
  '341': 1.0399186,
  '3443': 0.547093,
  '361': 0.3313275,
  '601': 0.5318834,
  '605': 0.2909876}]

1 个答案:

答案 0 :(得分:3)

这是一种方法。我将你的例子简化为一个更容易推理的例子。

>>> dcts = [
... {1:2, 3:4, 5:6},
... {1:3, 6:7, 8:9},
... {6:10, 8:11, 9:12}]
>>> 
>>> [{k:v for k,v in d.items() if v == max(d.get(k) for d in dcts)} for d in dcts]
[{3: 4, 5: 6}, {1: 3}, {8: 11, 9: 12, 6: 10}]

编辑:

效率更高,因为每个键只计算一次max:

>>> from operator import or_
>>> from functools import reduce
>>> allkeys = reduce(or_, (d.viewkeys() for d in dcts))
>>> max_vals = {k:max(d.get(k) for d in dcts) for k in allkeys}
>>> result = [{k:v for k,v in d.items() if v == max_vals[k]} for d in dcts]
>>> result
[{3: 4, 5: 6}, {1: 3}, {8: 11, 9: 12, 6: 10}]