词典合并。我需要合并多个字典,例如:dict1 = {1:{"a":{A}}, 2:{"b":{B}}}dict2 = {2:{"c":{C}}, 3:{"d":{D}}带着A B C和D作为树的叶子,就像{"info1":"value", "info2":"value2"}有一个未知的水平(深度)字典,它可能是{2:{"c":{"z":{"y":{C}}}}}在我的例子中,它表示一个目录/文件结构,节点是docs,而叶是文件。我想将它们合并以获得: dict3 = {1:{"a":{A}}, 2:{"b":{B},"c":{C}}, 3:{"d":{D}}}我不知道如何用Python轻松地做到这一点。
3 回答
陪伴而非守候
TA贡献1757条经验 获得超8个赞
def mergedicts(dict1, dict2): for k in set(dict1.keys()).union(dict2.keys()): if k in dict1 and k in dict2: if isinstance(dict1[k], dict) and isinstance(dict2[k], dict): yield (k, dict(mergedicts(dict1[k], dict2[k]))) else: # If one of the values is not a dict, you can't continue merging it. # Value from second dict overrides one in first and we move on. yield (k, dict2[k]) # Alternatively, replace this with exception raiser to alert you of value conflicts elif k in dict1: yield (k, dict1[k]) else: yield (k, dict2[k])dict1 = {1:{"a":"A"},2:{"b":"B"}}dict2 = {2:{"c":"C"},3:{"d":"D"}}print dict(mergedicts(dict1,dict2))
{1: {'a': 'A'}, 2: {'c': 'C', 'b': 'B'}, 3: {'d': 'D'}}
守着星空守着你
TA贡献1799条经验 获得超8个赞
class YamlReaderError(Exception): passdef data_merge(a, b): """merges b into a and return merged result NOTE: tuples and arbitrary objects are not handled as it is totally ambiguous what should happen""" key = None # ## debug output # sys.stderr.write("DEBUG: %s to %s\n" %(b,a)) try: if a is None or isinstance(a, str) or isinstance(a, unicode) or isinstance(a, int) or isinstance(a, long) or isinstance(a, float): # border case for first run or if a is a primitive a = b elif isinstance(a, list): # lists can be only appended if isinstance(b, list): # merge lists a.extend(b) else: # append to list a.append(b) elif isinstance(a, dict): # dicts must be merged if isinstance(b, dict): for key in b: if key in a: a[key] = data_merge(a[key], b[key]) else: a[key] = b[key] else: raise YamlReaderError('Cannot merge non-dict "%s" into dict "%s"' % (b, a)) else: raise YamlReaderError('NOT IMPLEMENTED "%s" into "%s"' % (b, a)) except TypeError, e: raise YamlReaderError('TypeError "%s" in key "%s" when merging "%s" into "%s"' % (e, key, b, a)) return a
替换标量 附加列表 通过添加缺失键和更新现有键来合并DECTS
添加回答
举报
0/150
提交
取消