Merge two dictionaries and keep the values for duplicate keys in Python

前端 未结 8 2301
广开言路
广开言路 2021-02-08 19:16

Let\'s suppose that I have two dictionaries:

dic1 =  { \"first\":1, \"second\":4, \"third\":8} 
dic2 =  { \"first\":9, \"second\":5, \"fourth\":3}
8条回答
  •  醉话见心
    2021-02-08 19:45

    from copy import deepcopy
    
    
    def _add_value_to_list(value, lis):
        if value:
            if isinstance(value, list):
                lis.extend(value)
            else:
                lis.append(value)
        else:
            pass
    
    
    def _merge_value(value_a, value_b):
        merged_value = []
        _add_value_to_list(value_a, merged_value)
        _add_value_to_list(value_b, merged_value)
        return merged_value
    
    
    def _recursion_merge_dict(new_dic, dic_a, dic_b):
        if not dic_a or not dic_b:
            return new_dic
        else:
            if isinstance(new_dic, dict):
                for k, v in new_dic.items():
                    new_dic[k] = _recursion_merge_dict(v, dic_a.get(k, {}), dic_b.get(k, {}))
                return new_dic
            else:
                return _merge_value(dic_a, dic_b)
    
    
    def merge_dicts(dic_a, dic_b):
        new_dic = deepcopy(dic_a)
        new_dic.update(dic_b)
    
        return _recursion_merge_dict(new_dic, dic_a, dic_b)
    

提交回复
热议问题