spjrual spjrual - 1 month ago 9
Python Question

Group the attributes of the objects in the array

In an array, the orderly storage of some objects, each object has a name is the "group" attribute,How to group objects by "group" attribute,encountered group value is 0 as the same group, until encountered group is other value , At last Get a dictionary

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'} ]


I expect this result is

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'} ]
}

Answer Source

This might work as you expect, using OrderedDict to keep the order of source input :

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'}])])