2012-10-10 19 views
9
d = { 
    "local": { 
     "count": 1, 
     "health-beauty": { 
      "count": 1, 
      "tanning": {"count": 1} 
     } 
    }, 
    "nationwide": {"count": 9.0}, 
    "travel": {"count": 0} 
}  

この場合、"nationwide"が最大です。ネストされたディクショナリで最大値を見つける

コードは、それが簡単にスクリプトにアタッチさせるには、以下である:

d = {'travel': {'count': 0}, 'local': {'count': 1, 'health-beauty': {'count': 1, 'tanning': {'count': 1}}}, 'nationwide': {'count': 9.0}} 
+0

は、キー= 'プリントMAX(D、見ていましたラムダx:x [1]) ' – AlexZ

+1

あなたは最大のlocal.tanningを作ったはずです...答えが見つからないので... –

+0

"日焼け "が10で、それを捕らえなければならない場合は、辞書を平坦化する必要があるかもしれません。このようなものを試してみてください[http://stackoverflow.com/questions/6027558/flatten-nested-python-dictionaries-compressing-keys](http://stackoverflow.com/questions/6027558/flatten-nested-python-dictionaries- –

答えて

10
>>> max(d, key=lambda x: d[x]['count']) 
'nationwide' 
+1

伝説!ほとんどの場合、このためにありがとうございました – AlexZ

+2

これはうまくいきません..内部ディクテーションが最大であると言うと(それはネストされたディクショナリを考慮しないので) –

+1

ジョラン:カウントが各子に対してインクリメントされます... – AlexZ

1

これは、ネストされた辞書のために働く必要があります。

def find_max(d, name=None): 
    return max((v, name) if k == "count" else find_max(v, k) for k, v in d.items()) 

>>> find_max(d) 
(9.0, 'nationwide') 
+1

私は思っていません...ローカルは、それぞれが自分のカウントを持っているキーカウントとより多くのエントリを持っています... –

+0

@JoranBeasley固定 – defuz

+0

素敵な仕事:) ... –

関連する問題