Convert (sorted) list of dics to nested list ?

shearichard at gmail.com shearichard at gmail.com
Tue Mar 21 12:57:46 CET 2006


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


Well I've now been around the block a few times with this one and I'm
still frowning !! In the process my code has become uglier and uglier -
I'm sure there must be quite an elegant way of dealing with it - could
anyone give me a push in the right direction ?

Just to provide some motivation here - I should just say that this is
cut down test case - the real problem involves creating a Javascript
structure which in turn defines a three level menu.

The resulting JS will be something like this, I think you can see how
the nested loops get into it.:

var MENU_ITEMS = [
    { pos:'relative', leveloff:[b,a], itemoff:[d,c], size:[e,f], ... },
    { ...Item 1... },
    { ...Item 2... ,
        sub:[
            { ...level format... },
            { ...Item 1... },
            { ...Item 2... },
            { ...Item 3... ,
                sub:[
                    { ...level format... },
                    { ...Item 1... },
                    { ...Item 2... },
                    { ...Item 3... },
                    { ...Item 4... }
                ]
            },
            { ...Item 4... },
        ]
    },
    { ...Item 3... }
];

Interested to hear of any smart/elegant ideas.

thanks

Richard.




More information about the Python-list mailing list