How to merge dictionaries of dictionaries?

后端 未结 29 3170
渐次进展
渐次进展 2020-11-22 05:13

I need to merge multiple dictionaries, here\'s what I have for instance:

dict1 = {1:{\"a\":{A}}, 2:{\"b\":{B}}}

dict2 = {2:{\"c\":{C}}, 3:{\"d\":{D}}
         


        
29条回答
  •  春和景丽
    2020-11-22 06:01

    class Utils(object):
    
        """
    
        >>> a = { 'first' : { 'all_rows' : { 'pass' : 'dog', 'number' : '1' } } }
        >>> b = { 'first' : { 'all_rows' : { 'fail' : 'cat', 'number' : '5' } } }
        >>> Utils.merge_dict(b, a) == { 'first' : { 'all_rows' : { 'pass' : 'dog', 'fail' : 'cat', 'number' : '5' } } }
        True
    
        >>> main = {'a': {'b': {'test': 'bug'}, 'c': 'C'}}
        >>> suply = {'a': {'b': 2, 'd': 'D', 'c': {'test': 'bug2'}}}
        >>> Utils.merge_dict(main, suply) == {'a': {'b': {'test': 'bug'}, 'c': 'C', 'd': 'D'}}
        True
    
        """
    
        @staticmethod
        def merge_dict(main, suply):
            """
            获取融合的字典,以main为主,suply补充,冲突时以main为准
            :return:
            """
            for key, value in suply.items():
                if key in main:
                    if isinstance(main[key], dict):
                        if isinstance(value, dict):
                            Utils.merge_dict(main[key], value)
                        else:
                            pass
                    else:
                        pass
                else:
                    main[key] = value
            return main
    
    if __name__ == '__main__':
        import doctest
        doctest.testmod()
    

提交回复
热议问题