1

My problem is how to map dictionary values to row indices. I have a dictionary like:

ordered_dict = OrderedDict(1:"id", 2:"name", 3:"address", 4:"salary")

And I got rows from a select query like:

row = ["David", 4500, "France", 121]

With the following code, where i get id as first index in dictionary, which is fourth in case of row, I want to map them such that variable value will actually get the values from the id of the row.

for item in ordered_dict.iteritems:
    value = row[index of current item in dictionary] # which is 1 for the id.

But I want the index of id in a row. ie.

value = row[index of id in row]  # that is, value = row [4]

so that i can retrieve the value of id from row, which is 121.

I can not break the current structure of the dictionary or the select query, so I am looking for a way to map the row items to the dictionary.

Edit: In the above code what I get in the first iteration is

  value = row[0] # here 0 is the id of dictionary,

But if row[0] will retrieve "David" as index 0 of row contains "David", I want the index of id to be mapped with row, which is 3 in my example, so that I will get value = row[3], here 3 is index of id in row, and hence I will get 121 as the result.

4

1 回答 1

3

这应该做的工作:

results = cursor.fetchall()
col_names = [column[0] for column in cursor.description]
rows_dict = map(lambda row: dict(zip(col_names, row)), results)

它适用于 PostgreSQL 和 SQLite3,但我尚未使用 MySQL 对其进行测试。如果发生 postgres IndexError 或类似情况,请尝试更改第二行:

col_names = [column.name for column in cursor.description]
于 2011-08-03T09:20:44.870 回答