Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.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 将元组列表转换为Dict时,Dict输出完全混乱_Python_Dictionary_Mysql Python - Fatal编程技术网

Python 将元组列表转换为Dict时,Dict输出完全混乱

Python 将元组列表转换为Dict时,Dict输出完全混乱,python,dictionary,mysql-python,Python,Dictionary,Mysql Python,我正在处理数据库查询结果。输出如下所示: {'col1':1,'col2':2,'col3':3} {'col1':4,'col2':5,'col3':6} [{'col2': 2, 'col3': 3, 'col1': 1}, {'col2': 5, 'col3': 6, 'col1': 4}, {'col2': 8, 'col3': 9, 'col1': 7}, {'col2': 2, 'col3': 3, 'col1': 1}, {'col2': 5, 'col3': 6, 'col1'

我正在处理数据库查询结果。输出如下所示:

{'col1':1,'col2':2,'col3':3}
{'col1':4,'col2':5,'col3':6}
[{'col2': 2, 'col3': 3, 'col1': 1}, {'col2': 5, 'col3': 6, 'col1': 4}, {'col2': 8, 'col3': 9, 'col1': 7}, {'col2': 2, 'col3': 3, 'col1': 1}, {'col2': 5, 'col3': 6, 'col1': 4}, {'col2': 8, 'col3': 9, 'col1': 7}]
rows=[(1,2,3)、(4,5,6)、(7,8,9)]

也就是说,数据库中有3行表数据

列名称如下所示:

{'col1':1,'col2':2,'col3':3}
{'col1':4,'col2':5,'col3':6}
[{'col2': 2, 'col3': 3, 'col1': 1}, {'col2': 5, 'col3': 6, 'col1': 4}, {'col2': 8, 'col3': 9, 'col1': 7}, {'col2': 2, 'col3': 3, 'col1': 1}, {'col2': 5, 'col3': 6, 'col1': 4}, {'col2': 8, 'col3': 9, 'col1': 7}]
cols=['col1','col2','col3']

我想用它们列一个字典列表,如下所示:

{'col1':1,'col2':2,'col3':3}
{'col1':4,'col2':5,'col3':6}
[{'col2': 2, 'col3': 3, 'col1': 1}, {'col2': 5, 'col3': 6, 'col1': 4}, {'col2': 8, 'col3': 9, 'col1': 7}, {'col2': 2, 'col3': 3, 'col1': 1}, {'col2': 5, 'col3': 6, 'col1': 4}, {'col2': 8, 'col3': 9, 'col1': 7}]
所以我这样做了:

res=[]
for row in rows:
  res.append(dict(zip(cols,row)))
但是res是这样的:

{'col1':1,'col2':2,'col3':3}
{'col1':4,'col2':5,'col3':6}
[{'col2': 2, 'col3': 3, 'col1': 1}, {'col2': 5, 'col3': 6, 'col1': 4}, {'col2': 8, 'col3': 9, 'col1': 7}, {'col2': 2, 'col3': 3, 'col1': 1}, {'col2': 5, 'col3': 6, 'col1': 4}, {'col2': 8, 'col3': 9, 'col1': 7}]
我不明白为什么键值对不是按列名排列的。
这不是一个大问题,我可以按键名对dict元素进行排序,但是我首先要如何使它们有序,而不需要对它们进行排序?

如果您想保持顺序,可以使用集合中的有序字典(orderedict

import collections

rows = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
cols = ['col1', 'col2', 'col3']

res = []
for row in rows:
    res.append(collections.OrderedDict(zip(cols,row)))
输出为:

[OrderedDict([('col1', 1), ('col2', 2), ('col3', 3)]),
 OrderedDict([('col1', 4), ('col2', 5), ('col3', 6)]),
 OrderedDict([('col1', 7), ('col2', 8), ('col3', 9)])]

如果您想保持顺序,最好创建一个二维元组列表一般来说,dict键是没有顺序的。在另一个体系结构和另一个Python解释器中,您可能会得到不同的结果。@sshashank124实际上我需要以JSON格式输出结果。因此,
dict
您不能对字典进行排序,因为它们只是较低级别的哈希映射。它们不需要订购。如果您发现需要订购,通常不应该使用。@AlexThornton嘿,谢谢。事实上,我真的不需要订购。因为在另一端,我将作为JSON数据访问它,我真的不在乎。无论如何,我只需要访问键值对。我猜是我的强迫症在唠叨我,让我点了。是的,谢谢,但我已经知道了。