将字典与行值映射
我的问题是如何将字典值映射到行索引。我有一个像这样的字典:
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.
但我想要 id
的索引位于 row
中。 IE。
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 作为结果。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这应该可以完成工作:
它适用于 PostgreSQL 和 SQLite3,但我还没有用 MySQL 测试过它。如果发生 postgres IndexError 或类似的情况,请尝试更改第二行:
This should do the work:
It's working for PostgreSQL and SQLite3, but I haven't tested it with MySQL. If for postgres IndexError or something like this occurs, try changing second line on: