2014-11-06 64 views
1

我在数据库列表中使用MySQLdb从我的数据库中得到'n'个记录。我想根据数据将列表分成不同的子列表。例如在Python中将字典的列表划分为子字典

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 

我想这个数据转换成:

col1 | col2 | col3 | col4 

1日列表:

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 

有Python语言组多列和分裂清单分成多个列出任何超真棒方式。

编辑:

目前,我有:

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

我想这些子数据分成取决于存在于col1和COL2值的字典的列表。

您可以从上表中了解它。我猜输出将是[[{}]]格式。

+0

那么你想要将字典列表转换为列表的列表?你可以更新你的问题与示例python数据结构如何访问输出? – user3885927 2014-11-06 06:05:15

+0

@ user3885927我按照您的要求编辑了问题。 – SiMemon 2014-11-06 06:24:15

回答

1

字典使用字典:

super_awesome = {} 
for row in rows: # these are the rows from MySQLdb 
    col1 = super_awesome.get(row['col1'], {}) # get col1 or an empty dict 
    col2 = col1.get(row['col2'], [])    # get col2 or an empty list 
    col2.append(row)        # append row to (col1,col2) 
    col1[row['col2']] = col2      # put col2 into col1 
    super_awesome[row['col1']] = col1   # put col1 into super_awesome 

当你完成后,super_awesome对每个唯一col1值的条目,每个条目那些具有用于每个唯一(col1,col2)值的条目。反过来,这些条目每个都有一个(col1,col2)对的行列表。

+0

根据您的回答,我可以在[[{}]]数据类型中获得输出而不是{{[{}]}}吗? – SiMemon 2014-11-06 06:55:50

+0

我会留给你的。 – 2014-11-06 15:17:06