python,list嵌套多个元素不相同的dict进行分组合并

找了半天也没汇总的好办法只能自己写一个

实现如下

list1=[

{'id':'A'apple':99,'orange‘:20},

{'id':'A',apple':100,'Banana‘:50},

{'id':'B,'Banana‘:50},

{'id':'B,'Banana‘:10,'orange‘:30,'Cherry':2},

]

输出

[{'id':'A','apple':199,'orange‘:20','Banana':50,'Cherry':0},

{'id':'B','apple':0,'orange‘:30','Banana':60,'Cherry':2}]

m=MyListDictGroup(list1)

m_g=m.groupby(groupbyKey='id',('id',),completion=True,defaultValues=0)

#-*- coding:utf-8 -*-

class MyListDictGroup(object):
    '''把列表中嵌套的多个Dict进行分组计算'''
    def __init__(self,_data:list,):
        self._data=_data
        self.__dataInit()

    def __dataInit(self):
        self._data_len=len(self._data)
        if self._data_len<=0:
            raise print('数组长度获取失败')

        self._data_all_keys=dict()
        for _k in self._data:
            self._data_all_keys.update(_k)

    def __getNullAllKeysDict(self,defaultValues=0)->dict:
        _r=dict()
        for _k in self._data_all_keys.keys():
            _r.update({_k:defaultValues})
        return _r


    def groupby(self,groupbyKey:str,nokeys:tuple=(None),completion:bool=True,defaultValues=0)->list:
        '''进行分组
        groupbyKey用来分组的字段,必须有
        nokeys:tuple 不进行计算的字段
        completion 是否补齐字段
        defaultValues 补齐默认数值
        '''
        if not bool(nokeys):
            nokeys=(groupbyKey,)
        self.groupbyKey = groupbyKey
        _tempKeys = []
        for _i in self._data:
            if not self.groupbyKey in _i.keys():
                raise print('{0}\n行不存在要分组的key'.format(str(_i)))
            _tempKeys.append(_i.get(self.groupbyKey))

        try:
            self.groupbyKeySet = set(_tempKeys)
        except BaseException as e:
            print('要分组的结果列表转换失败', e)

        _temp_all_list=[]
        for _byKey in self.groupbyKeySet:
            if completion:
                _temp_key_dict= {groupbyKey:_byKey}
            else:
                _temp_key_dict=self.__getNullAllKeysDict(defaultValues)
            _temp_key_dict[groupbyKey]=_byKey
            for _d in self._data:
                if _byKey==_d[groupbyKey]:
                    #_temp_key_dict=self.__dictadd(_temp_key_dict,_d,(groupbyKey,))
                    _temp_key_dict = self.__dictadd(_temp_key_dict, _d, nokeys)
            _temp_all_list.append(_temp_key_dict)
        return _temp_all_list

    def __dictadd(self,o_Dict: dict, addDict: dict,NoKeys:tuple) -> dict:
        r_dict = o_Dict.copy()
        for key in addDict.keys():
            if key in NoKeys:
                continue
            if not o_Dict.get(key):
                r_dict.update({key: addDict.get(key)})
            else:
                try:
                    __ov = o_Dict.get(key)
                    __nv = addDict.get(key)
                    r_dict.update({key: __ov + __nv})
                except:
                    r_dict.update({key: addDict.get(key)})
        return r_dict

    def merge(self,o_list: list, a_list: list, indexKey: str)->list:
        '''根据key合并两个list嵌套的字典'''
        if not o_list or not a_list or not indexKey:
            raise print('要合并的为空')
        _r_list = []
        for _o in o_list:
            _temp_dict = _o.copy()
            for _k in a_list:
                if str(_o.get(indexKey)) == str(_k.get(indexKey)):
                    _temp_a_dict = _k.copy()
                    _temp_a_dict.pop(indexKey)
                    _temp_dict.update(_temp_a_dict)
            _r_list.append(_temp_dict)
        return _r_list

你可能感兴趣的:(python,list)