Convert (sorted) list of dics to nested list ?

Gerard Flanagan grflanagan at yahoo.co.uk
Wed Mar 22 16:34:57 EST 2006


shearichard at gmail.com wrote:

> Hi - I want to take something like ...
>
> lstIn = []
> lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 10, 'LEA_AUTOID': 1000})
> lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 11, 'LEA_AUTOID': 2000})
> lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 11, 'LEA_AUTOID': 2001})
> lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 11, 'LEA_AUTOID': 2003})
> lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 12, 'LEA_AUTOID': 3000})
> lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 12, 'LEA_AUTOID': 3001})
> lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 12, 'LEA_AUTOID': 3002})
> lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 12, 'LEA_AUTOID': 3003})
> lstIn.append({'COM_AUTOID': 2, 'PRG_AUTOID': 110, 'LEA_AUTOID': 4000})
>
>
> ... and produce something like ...
>
> sampleOut =
> [[1,[10,1000]],[1,[11,[2000,2001,2003]]],[1,[12,[3000,3001,3002,3003]]],[2,[110,4000]]
>
>

lstIn = []
lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 10, 'LEA_AUTOID': 1000})
lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 11, 'LEA_AUTOID': 2000})
lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 11, 'LEA_AUTOID': 2001})
lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 11, 'LEA_AUTOID': 2003})
lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 12, 'LEA_AUTOID': 3000})
lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 12, 'LEA_AUTOID': 3001})
lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 12, 'LEA_AUTOID': 3002})
lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 12, 'LEA_AUTOID': 3003})
lstIn.append({'COM_AUTOID': 2, 'PRG_AUTOID': 110, 'LEA_AUTOID': 4000})

C="COM_AUTOID"
P="PRG_AUTOID"
L="LEA_AUTOID"

d = {}

# convert data to nested dictionary structure
for item in lstIn:
    c, p, l = item[C], item[P], item[L]
    if c not in d:
        d[c] = dict( {p : [l]} )
    else:
        if p not in d[c]:
            d[c][p] = [l]
        else:
            d[c][p].append(l)

def dict2list( adict ):
    for key in sorted(adict.keys()):
        if isinstance( adict[key], dict ):
            for item in dict2list(adict[key]):
                yield [key] + item
        else:
            yield [[key] + [adict[key]]]

result = list(dict2list(d))

cigar =
[[1,[10,1000]],[1,[11,[2000,2001,2003]]],[1,[12,[3000,3001,3002,3003]]],[2,[110,4000]]]
no_cigar =
[[1,[10,[1000]]],[1,[11,[2000,2001,2003]]],[1,[12,[3000,3001,3002,3003]]],[2,[110,[4000]]]]

assert result == no_cigar

print
print 'nested dict: ', d
print
print 'result: ', result

nested dict:  {1: {10: [1000], 11: [2000, 2001, 2003], 12: [3000, 3001,
3002, 3003]}, 2: {110: [4000]}}

result:  [[1, [10, [1000]]], [1, [11, [2000, 2001, 2003]]], [1, [12,
[3000, 3001, 3002, 3003]]], [2, [110, [4000]]]]

Gerard




More information about the Python-list mailing list