用行值映射字典
我的问题是如何将字典的值映射到行的索引。我有一个这样的字典:
ordered_dict = OrderedDict(1:"id", 2:"name", 3:"address", 4:"salary")
然后我从一个 select
查询中得到了行,像这样:
row = ["David", 4500, "France", 121]
在下面的代码中,我把 id
作为字典中的第一个索引,而在 row
中它是第四个。我想把它们映射起来,这样变量的值就能从 row
的 id
中获取。
for item in ordered_dict.iteritems:
value = row[index of current item in dictionary] # which is 1 for the id.
但我想要的是 row
中 id
的索引,也就是:
value = row[index of id in row] # that is, value = row [4]
这样我就可以从 row
中获取 id
的值,也就是 121
。
我不能改变字典的当前结构或 select
查询,所以我在寻找一种方法来将行的项目映射到字典。
编辑:在上面的代码中,我在第一次迭代中得到的是
value = row[0] # here 0 is the id of dictionary,
但是如果 row[0]
会返回 "David"
,因为索引 0
的 row
包含 "David"
,我想要将 id
的索引与 row
映射,这在我的例子中是 3
,这样我就能得到 value = row[3]
,这里的 3
是 row
中 id
的索引,因此我会得到 121
作为结果。
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上测试过。如果在PostgreSQL上出现IndexError或者类似的错误,可以尝试把第二行改成:
col_names = [column.name for column in cursor.description]