对数组中对象的属性进行分组

时间:2017-08-19 06:35:01

标签: python algorithm structure

在数组中,有些对象的有序存储,每个对象都有一个名称是" group"属性,如何按对象分组对象" group"属性,遇到的组值为0作为同一组,直到遇到组为其他值,最后获取字典

source = [ {'serial':'1','group':'0'}, {'serial':'2','group':'20'}, 
           {'serial':'3','group':'0'}, {'serial':'4','group':'0'}, 
           {'serial':'6','group':'33'}, {'serial':'7','group':'0'}, 
           {'serial':'8','group':'0'}, {'serial':'8','group':'18'} ] 

我希望这个结果是

Result = { '20':[ 
             {'serial':'2','group':'20'}, 
             {'serial':'3','group':'0'}, 
             {'serial':'4','group':'0'} ], 
          '33':[ 
             {'serial':'6','group':'33'}, 
             {'serial':'7','group':'0'}, 
             {'serial':'8','group':'0'} ], 
          '18':[ {'serial':'8','group':'18'} ] 
        } 

1 个答案:

答案 0 :(得分:0)

这可能会按预期工作,使用OrderedDict来保持源输入的顺序:

from collections import OrderedDict
result = OrderedDict()
group = None

for dic in source:
    if dic['group'] == '0':
        if group:
            result[group].append(dic)

    elif dic['group'] in result:
        result[dic['group']].append(dic)
    else:
        group = dic['group']
        result[dic['group']] = [dic]

>>> OrderedDict([('20',
              [{'group': '20', 'serial': '2'},
               {'group': '0', 'serial': '3'},
               {'group': '0', 'serial': '4'}]),
             ('33',
              [{'group': '33', 'serial': '6'},
               {'group': '0', 'serial': '7'},
               {'group': '0', 'serial': '8'}]),
             ('18', [{'group': '18', 'serial': '8'}])])