【问题标题】:Mapping dictionary with rows values使用行值映射字典
【发布时间】:2011-10-18 22:20:51
【问题描述】:

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

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

我从select 查询中得到了行,例如:

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

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

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

但我想要row 中的id 的索引。 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" 作为row 的索引0 包含"David",我希望id 的索引与row 映射,即我的3例如,我会得到value = row[3],这里3rowid的索引,因此我会得到121

【问题讨论】:

  • 我不明白你的问题。您能否提供预期的输出?
  • 您可以发布您的查询以检索数据吗?您可以在查询中选择列时进行所需的顺序,以便它可以与字典进行映射
  • 我用预期的输出编辑了我的帖子。
  • @Aamir Adnan:问题是我无法更改现有选择查询的结构。

标签: python mapping ordereddictionary


【解决方案1】:

这应该可以完成工作:

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]

【讨论】:

    猜你喜欢
    • 2020-09-01
    • 2021-08-02
    • 2011-08-25
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2018-09-09
    • 2010-09-12
    • 2021-12-27
    相关资源
    最近更新 更多