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의 값을 유지
'dict'은 사전에 조합하려는 유일한 "특수"유형입니까? – robert
@antti : 중첩 수준 (깊이)은 사전에 알고 있기 때문에이 질문에 더 쉬운 해결책이 될 것이라고 생각합니다 (이 경우에만 2) – blues
@robert : 예. just dicts – blues