简体   繁体   English

根据嵌套字典 python 的值获取键

[英]Get key depending on value of nested dictionary python

I've a nested-nested dictionary like:我有一个嵌套嵌套字典,例如:

d = {1: {490: {'angle': 0.9439585203011613,
       'distance': 0.10334710770757652,
       'gid': 19675.0,
       'index': 1.3627196218429294,
       'length': 0.3154139938341916},
 491: {'angle': 0.6009780397464144,
       'distance': 0.1914804717173812,
       'gid': 19679.0,
       'index': 0.8333609923300924,
       'length': 0.04090248086629692},
 492: {'angle': 0.9299210633144231,
       'distance': 0.1392632853868988,
       'gid': 19680.0,
       'index': 1.1225744054577835,
       'length': 0.053390056756461614},
 493: {'angle': 0.9499097709829176,
       'distance': 0.16460473640157167,
       'gid': 19681.0,
       'index': 1.6564270961214378,
       'length': 0.5419125887369485}}}

what I would like to get is the nested key (490, 491, 492, 493) where the nested-nested value of the index key is the lowest.我想得到的是嵌套键(490、491、492、493),其中index键的嵌套嵌套值最低。 Basically:基本上:

for k, v in d.items():
    for kk, vv in v.items():
        print(kk, vv['index'])

490 1.3627196218429294
491 0.8333609923300924
492 1.1225744054577835
493 1.6564270961214378

the value I want is 491 .我想要的值是491

I'm stuck with the usage of min .我坚持使用min I know the trick should be in the min function and the usage of the key parameter, but I'm getting confused how to use it correctly within this nested situation.我知道诀窍应该在min function 和key参数的使用中,但我对如何在这种嵌套情况下正确使用它感到困惑。

If d is your dictionary from the question:如果d是问题中的字典:

mn = min(
    [(i, k) for i in d.values() for k in i],
    key=lambda k: k[0][k[1]]["index"],
)
print(mn[1])

Prints:印刷:

491

use pandas -使用 pandas -

import pandas as pd
print(pd.DataFrame(d[1]).transpose().sort_values('index').head(1).index) #491

use the key as the index value of each sub dictionary.使用该键作为每个子字典的索引值。

min(d[1],key=lambda x:d[1][x]['index'])

note that d[1] is used here, the d dictionary only has one key.注意这里使用了d[1]d字典只有一个键。

generate the list of minimums on a full dictionary like this:在完整字典上生成最小值列表,如下所示:

[min(subd,key=lambda x:subd[x]['index']) for subd in d.values()]

and as a dictionary:作为字典:

{k:min(subd,key=lambda x:subd[x]['index']) for k,subd in d.items()}

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

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