Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 具有行值的映射字典_Python_Mapping_Ordereddictionary - Fatal编程技术网

Python 具有行值的映射字典

Python 具有行值的映射字典,python,mapping,ordereddictionary,Python,Mapping,Ordereddictionary,我的问题是如何将字典值映射到行索引。我有一本字典,像: ordered_dict = OrderedDict(1:"id", 2:"name", 3:"address", 4:"salary") 我从一个select查询中得到了如下行: row = ["David", 4500, "France", 121] 在下面的代码中,我将id作为字典中的第一个索引,在行的情况下,这是第四个索引,我希望映射它们,以便变量值将实际从行的id中获取值 for item in ordered_dict.it

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

ordered_dict = OrderedDict(1:"id", 2:"name", 3:"address", 4:"salary")
我从一个
select
查询中得到了如下行:

row = ["David", 4500, "France", 121]
在下面的代码中,我将
id
作为字典中的第一个索引,在
的情况下,这是第四个索引,我希望映射它们,以便变量值将实际从
id
中获取值

for item in ordered_dict.iteritems:
    value = row[index of current item in dictionary] # which is 1 for the id.
但是我希望
id
的索引位于
行中
。即

value = row[index of id in row]  # that is, value = row [4]
这样我就可以从
中检索
id
的值,即
121

我无法破坏字典的当前结构或
select
查询,因此我正在寻找将行项目映射到字典的方法

编辑:在上面的代码中,我在第一次迭代中得到的是

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

但是,如果
行[0]
将检索
“David”
,因为
行的
0
索引包含
“David”
,我希望
id
的索引映射到
行,在我的示例中是
3
,这样我将得到
值=行[3]
,这里
3
行中
id
的索引,因此我将得到
121

这应该可以完成以下工作:

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 Indexer或类似情况,请尝试在以下位置更改第二行:

col_names = [column.name for column in cursor.description]

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