Sunday, 15 July 2012

Divide list of dictionary into sub dictionary in Python -



Divide list of dictionary into sub dictionary in Python -

i 'n' number of records database using mysqldb in list of dictionary. want sub split list different sub list depending upon data. e.g.

col1 | col2 | col3 | col4 data11 | data12 | data13 | data14 data11 | data12 | data23 | data24 data11 | data13 | data33 | data34 data11 | data13 | data43 | data44 data21 | data12 | data53 | data54 data21 | data12 | data63 | data64 data21 | data13 | data73 | data74 data21 | data13 | data83 | data84

i want convert info into:

col1 | col2 | col3 | col4

1st list:

data11 | data12 | data13 | data14 data11 | data12 | data23 | data24

2nd list:

data11 | data13 | data33 | data34 data11 | data13 | data43 | data44

3rd list:

data21 | data12 | data53 | data54 data21 | data12 | data63 | data64

4th list:

data21 | data13 | data73 | data74 data21 | data13 | data83 | data84

is there super awesome way of python grouping multiple columns , split list multiple lists.

edit:

currently, have:

[{ "col1":"data11","col2":"data12","col3":"data13","col4":"data14" }, ... ]

i want sub split these info list of dictionary depending on values nowadays in col1 , col2.

you can understand table above. guess output in [[{}]] format.

use dictionaries of dictionaries:

super_awesome = {} row in rows: # these rows mysqldb col1 = super_awesome.get(row['col1'], {}) # col1 or empty dict col2 = col1.get(row['col2'], []) # col2 or empty list col2.append(row) # append row (col1,col2) col1[row['col2']] = col2 # set col2 col1 super_awesome[row['col1']] = col1 # set col1 super_awesome

when you're done, super_awesome has entry each unique col1 value, , each of entries has entry each unique (col1,col2) value. in turn, entries each have list of rows (col1,col2) pair.

python python-2.7 dictionary

No comments:

Post a Comment