将字典与行值映射

发布于 2024-11-27 16:00:16 字数 1211 浏览 2 评论 0原文

我的问题是如何将字典值映射到行索引。我有一个像这样的字典:

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

并且我从 select 查询中获取了行,例如:

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

使用以下代码,我将 id 作为字典中的第一个索引,这是第四个索引的 row 中,我想映射它们,以便变量值实际上从 rowid 中获取值。

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],这里 3rowid 的索引,因此我会得到 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜吻♂芭芘 2024-12-04 16:00:16

这应该可以完成工作:

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]

This should do the work:

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

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:

col_names = [column.name for column in cursor.description]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文