Reputation: 4921
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. 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
.
I'm stuck with the usage of 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.
Upvotes: 0
Views: 64
Reputation: 140307
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.
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()}
Upvotes: 0
Reputation: 14949
use pandas -
import pandas as pd
print(pd.DataFrame(d[1]).transpose().sort_values('index').head(1).index) #491
Upvotes: 0
Reputation: 195613
If d
is your dictionary from the question:
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
Upvotes: 1