2014-01-30 44 views
0

我有一個數據庫表有多個字段,我正在查詢並提取符合某些參數的所有數據。我使用的psycopg2的Python語法如下:從PostgreSQL獲取數據爲字典

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

這將返回正確的值與數據的完整性和秩序維護的列表。不過,我想查詢在我的應用程序的其他地方返回的列表,我只有這個值的列表,即它不是一個字段的字段作爲這些值的鍵。而不是做

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

我希望能夠通過類似的字段名查詢:

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

有沒有一種簡單的方法和有效的方式做到這一點?

謝謝!

+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()