2014-01-30 7 views
0

나는 특정 매개 변수를 충족시키는 모든 데이터를 쿼리하고 추출하는 여러 필드가있는 데이터베이스 테이블을 가지고 있습니다. 나는 다음과 같은 구문을 사용하여 파이썬에 대한 psycopg2을 사용하고 있습니다 :PostgreSQL에서 사전으로 데이터 가져 오기

cur.execute("SELECT * FROM failed_inserts where insertid='%s' AND site_failure=True"%import_id) 
       failed_sites= cur.fetchall() 

이 유지 관리되는 데이터의 무결성과 순서 목록으로 올바른 값을 반환합니다. 그러나 내 응용 프로그램에서 다른 곳에서 반환 된 목록을 쿼리하고 싶습니다. 그리고이 값 목록 만 가지고 있습니다. 즉,이 값의 키로 필드가있는 사전이 아닙니다. 간단한 방법 및이를위한 효율적인 방법이 있나요

desiredValue = failed_sites[fieldName] //where fieldName is the name of the field I am looking for 

: 오히려 내가 좋아하는 필드 이름으로 조회 할 수 있도록하려면

desiredValue = failed_sites[13] //where 13 is an arbitrary number of the index for desiredValue 

을 수행하는 것보다?

감사합니다.

+1

http://www.python.org/dev/peps/pep-0249/#frequently-asked-questions를 참조하십시오. –

답변

1

cursor.description은 열 정보 (http://www.python.org/dev/peps/pep-0249/#cursor-objects)를 제공합니다. 열 이름을 가져 와서 사전을 만들 때 사용할 수 있습니다.

cursor.execute('SELECT ...') 
columns = [] 
for column in cursor.description: 
    columns.append(column[0].lower()) 
failed_sites = {} 
for row in cursor: 
    for i in range(len(row)): 
     failed_sites[columns[i]] = row[i] 
     if isinstance(row[i], basestring): 
      failed_sites[columns[i]] = row[i].strip() 
관련 문제