Skip to main content
 首页 » 编程设计

python之如何在多层 python 字典中找到最小值,以及它的 "path"(即叶值的键列表)

2025年05月04日9lonelyxmas

我有以下格式的 python 字典:

d =  
{ 
  'category' : 
  { 
    'genre': <int_value> 
  } 
} 

我想找到最小的<int_value> ,以及原始字典中的“路径”。

例如如果

d =  
{ 
  'free': 
  { 
    'adventure' : 23, 
    'arcade' : 101, 
  }, 
  'paid': 
  { 
    'arcade' : 130, 
  } 
} 

...结果应该是("free", "adventure", 23) .

谁能想到一个单行代码?

提前致谢!

请您参考如下方法:

print min((d[c][x], c, x) for c in d for x in d[c]) 

并重新安排:

print min( (d[c][x], x, c) for c in d for x in d[c] )[::-1]