2012-11-21 3 views
1

가능한 중복 : 멀티 레벨이
Checking a Dictionary using a dot notation string모범 사례 얻을 멀티 레벨 딕셔너리에 값을 설정하는

같이 DICT :

some_infomations = { 
    "root":{ 
     "sub":{ 
      "more_deep":{ 
       "not_enough": "Some value", 
       "another": "bla..bla" 
      } 
     }, 
     "more":{ 
      "more_deep":{ 
       "not_enough": "Some value", 
       "another": "bla..bla" 
      } 
     } 
    } 
} 

나는 바보 같은 문자열을 root.sub.more_deep.another과 같은 일을 할 수있는 간단하고 좋은 방법입니다 eval("some_infomations[root.sub.more_deep.another] = some_value")? reduce이 더 많은 사용을 가지고 있기 때문에

+1

비슷한 질문 : http://stackoverflow.com/q/12414821/1639625 –

+0

를 의견에 감사드립니다. :-) – kimjxie

답변

0

주로 재미를 위해 여기에 게시 뿐만 아니라 대부분의 사람들을 위해 ... 그것에게 신용을 제공보다 :

from operator import getitem 
def dot_get(your_dict,s): 
    return reduce(getitem, s.split('.'), your_dict) 

d = {'foo': {'bar': {'baz': 1}}} 
print dot_pull(d,'foo.bar.baz') 

편집 - 분명히이 영업 이익에 그것을 어떻게입니다 이전 질문은 제가 OPE가 dict.get을 사용했지만 KeyError를 억제 할지라도 충분히 신중하게 읽지는 못했습니다.

는 마지막 요소를 분할해야 것, 항목을 설정하고, 그 위의 한으로 활용하려면 다음

def dot_set(your_dict,s,v): 
    head,tail = s.rsplit('.',1) 
    dot_get(yourdict,head)[tail] = v 
+0

정확하게 내 대답의 형식을 지정하는 방법을 모르겠습니다. 여기에 붙여 넣었습니다 : https://gist.github.com/veverjak/72fa753f5e4234647835 – user1830432