2016-08-10 3 views
1

dict.getと同様に、ネストされた辞書にキーのタプルが存在するかどうか確認したいと思います。機能は以下のように達成することができる。キーツリーのネストされたdictsを検索する

nested_dict = { 
    'x': 1, 
    'a': { 
     'b': { 
      'c': 2, 
      'y': 3 
     }, 
     'z': 4 
    } 
} 

def check(nested, *path): 
    for key in path: 
     if isinstance(nested, dict) and key in nested: 
      nested = nested[key] 
     else: 
      return False 
    return True 


check(nested_dict, 'a', 'b', 'c') # True 
check(nested_dict, 'x') # True 
check(nested_dict, 'a', 'b', 'y') # True 
check(nested_dict, 'a', 'z') # True 

check(nested_dict, 'y') # False 
check(nested_dict, 'a', 'y') # False 
check(nested_dict, 'a', 'b', 'c', 'y') # False 

これを行うには、よりクリーンな方法(または組み込み済みの方法)がありますか?

答えて

1

python 3.xの場合from functools import reduce

あなたがラップすることができますtry .. except KeyError(およびTypeError)と、適切なブール値を返します。

>>> reduce(lambda x,y: x[y], ["a", "b", "c"], nested_dict) 
2 
>>> reduce(lambda x,y: x[y], ["a", "b", "d"], nested_dict) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<stdin>", line 1, in <lambda> 
KeyError: 'd' 

PS:これらの1行は時々書くための楽しいです。しかし、私は正直なところあなたのバージョンを任意のプロダクションコードに使用します。

関連する問題