2012-05-22 6 views
4

가능한 중복 :에
python: Dictionaries of dictionaries merge파이썬, 병합 멀티 레벨 사전

my_dict= {'a':1, 'b':{'x':8,'y':9}} 
other_dict= {'c':17,'b':{'z':10}} 
my_dict.update(other_dict) 

결과 :

:

{'a': 1, 'c': 17, 'b': {'z': 10}} 

하지만 난이 원하는

{'a': 1, 'c': 17, 'b': {'x':8,'y':9,'z': 10}} 

어떻게하면됩니까? 파이썬 2.7 이상을 사용하지 않는 경우 (아마도 간단한 방법으로?)

+0

'dict'은 사전에 조합하려는 유일한 "특수"유형입니까? – robert

+0

@antti : 중첩 수준 (깊이)은 사전에 알고 있기 때문에이 질문에 더 쉬운 해결책이 될 것이라고 생각합니다 (이 경우에만 2) – blues

+0

@robert : 예. just dicts – blues

답변

5
import collections # requires Python 2.7 -- see note below if you're using an earlier version 
def merge_dict(d1, d2): 
    """ 
    Modifies d1 in-place to contain values from d2. If any value 
    in d1 is a dictionary (or dict-like), *and* the corresponding 
    value in d2 is also a dictionary, then merge them in-place. 
    """ 
    for k,v2 in d2.items(): 
     v1 = d1.get(k) # returns None if v1 has no value for this key 
     if (isinstance(v1, collections.Mapping) and 
      isinstance(v2, collections.Mapping)): 
      merge_dict(v1, v2) 
     else: 
      d1[k] = v2 

, 다음 (오리 입력의 경우) 또는 hasattr(v, "items") (고정 유형에 대한) isinstance(v, dict)isinstance(v, collections.Mapping)를 교체합니다. 즉, D1은 문자열 값을 가지고 있으며, D2는 해당 키에 대한 DICT 값이있는 경우 - - 일부 키의 충돌이 있다면 것을

참고 다음이 구현은 단지 (update 유사) D2의 값을 유지

+2

py2.7에서 isinstance (val, collections.Mapping)을 사용하는 것이 좋습니다. + –

+0

@ AnttiHaapala 좋은 제안. –

+0

이 작업을 수행합니다. 충돌하는 dicts 대 문자열/ints의 경우는 내가 dicts를 생성하는 데이터에서 발생할 수 없습니다. 감사 – blues