从嵌套字典中获取列的最大值

tp5buhyn  于 2021-09-08  发布在  Java
关注(0)|答案(2)|浏览(277)

下面的输出是我正在尝试使用的词典的一部分的漂亮打印快照。我希望输出列中所有条目的最高值 p ,以及它的主字典键。
在下面的输出示例中,的值 p 在里面 GRTEUR 高于的任何其他值 p 从任何其他主键,我想返回主键和值,所以 GRTEUR-0.1752234098475558 .
我读过关于Pandas和Pandas的书 pandas.DataFrame.max() 但我没有找到任何关于如何从键计算值的示例( p )嵌套字典的定义( 1h ).
有什么建议吗?

data = {
    "LUNAEUR": {
        "1h": {
            "ot": "2021-07-09 08:00:00",
            "o": 6.033,
            "h": 6.551,
            "l": 5.983,
            "ct": "2021-07-09 08:59:59.999000",
            "p": -1.660459342023591
        },
        "stream0": {
            "c": 6.444,
            "v": 1393.808,
            "ct": "2021-07-09 09:59:59.999000"
        },
        "stream1": {
            "c": 6.446,
            "v": 1171.177,
            "ct": "2021-07-09 09:59:59.999000"
        }
    },
    "THETAEUR": {
        "1h": {
            "ot": "2021-07-09 08:00:00",
            "o": 4.992,
            "h": 5.076,
            "l": 4.956,
            "ct": "2021-07-09 08:59:59.999000",
            "p": -0.2963841138114934
        },
        "stream0": {
            "c": 5.061,
            "v": 492.138,
            "ct": "2021-07-09 09:59:59.999000"
        },
        "stream1": {
            "c": 5.067,
            "v": 423.079,
            "ct": "2021-07-09 09:59:59.999000"
        }
    },
    "GRTEUR": {
        "1h": {
            "ot": "2021-07-09 08:00:00",
            "o": 0.5616,
            "h": 0.5717,
            "l": 0.5523,
            "ct": "2021-07-09 08:59:59.999000",
            "p": -0.1752234098475558
        },
        "stream0": {
            "c": 0.5707,
            "v": 105.17,
            "ct": "2021-07-09 09:59:59.999000"
        },
        "stream1": {
            "c": 0.571,
            "v": 19.71,
            "ct": "2021-07-09 09:59:59.999000"
        }
    }
}
a6b3iqyw

a6b3iqyw1#

使用python过滤数据 max(..., key=...) :

key, value = max(data.items(), key=lambda x: x[1]["1h"]["p"])
print(key, value["1h"]["p"])

要忽略那些值不包含“p”的键,可以提供一个非常小的默认值

import sys
max(data.items(), key=lambda x: x[1]["1h"].get("p", -sys.float_info.max))

或在查找最大值之前进行筛选:

max(((key, val) for key, val in data.items() if "p" in val["1h"]),
    key=lambda x: x[1]["1h"]["p"])
6fe3ivhb

6fe3ivhb2#

reduce函数给出每个字典中嵌套键的值。也许你可以试试这个:

def deep_get(dictionary, *keys):
  print(keys)
  return reduce(lambda d, key: d.get(key, None) if isinstance(d, dict) else None, keys, dictionary)

val_list=[]
key_list=["LUNAEUR","THETAEUR","GRTEUR"]
for item in key_list:
  key1=item
  key2='1h'
  key3='p'
  print(deep_get(data, key1,key2,key3))
  val_list.append(deep_get(data, key1,key2,key3))
  print(max(val_list)

Output:
-0.1752234098475558

相关问题