2014-11-06 2 views
1

사전 데이터베이스 목록에서 MySQLdb를 사용하여 데이터베이스에서 'n'개의 레코드를 얻습니다. 나는 데이터에 따라 다른 하위 목록으로 목록을 하위로 나누고 싶다. 예 :파이썬에서 사전 사전을 하위 사전으로 나누기

col1 | col2 | col3 | col4 

1 목록 :

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

2 목록 :

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

3 목록 :

012,351,641

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 

나는에이 데이터를 변환 할

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

4 목록 :

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

그룹 여러 열 및 여러 목록에 나누어 목록에 파이썬의 슈퍼 멋진 방법이 있나요.

EDIT :

가 현재 가지고 I : 하위에

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

I는 원하는 COL1과 COL2의 현재 값에 따라 사전의 목록으로 이러한 데이터를 나눈다.

위의 표에서 알 수 있습니다. 출력은 [[{}] 형식으로 표시됩니다. 사전

+0

그래서 사전 목록을 목록 목록으로 변환 하시겠습니까? 출력에 액세스하려는 방법에 대한 샘플 파이썬 데이터 구조로 질문을 업데이트 할 수 있습니까? – user3885927

+0

@ user3885927 귀하의 요청에 따라 질문을 편집했습니다. – SiMemon

답변

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

+0

나는 그것을 너에게 맡길 것이다. –

관련 문제