将字典附加到Python 3.7中的列表

问题描述 投票:1回答:3

问题

我有一个从MySQL数据库中提取数据的列表。使用SQLAlchemy

selectAA1 = conn.execute('
            SELECT YIELD_EXPECTED_QTY as x, YIELD_ACTUAL_QTY as y 
            FROM obj2mart')

我的成就是什么

keys = ["x", "y"]

values = []
for row in selectAA1:
    values.append(row[0])
    values.append(row[1])
print (values)

这段代码的结果是:

[3, 198, 3, 198, 3, 198, 3, 198, 3, 198, ...]

我想要的是有一个字典列表,将这些键映射到每个列表,即'x''y'

结果应该是字典列表:

[{ x: 3, y: 198 }, { x: 3, y: 198}, { x: 3, y: 198} , ...]

我做了什么

dictionary = {}
dictionary = dict(zip(keys, values))
print (dictionary)

但是,此代码只返回一个:

{ 'x': 3, 'y': 198 }

我是python的新手。有人能帮我吗?

注意:我使用的是Python 3.7

python list dictionary flask-sqlalchemy
3个回答
1
投票

我假设您的查询根据您引用行的方式返回列表列表。

这应该给你你想要的

dictionary = [dict(zip(keys, values)) for values in selectAA1]

1
投票

您可以尝试使用内置的_asdict方法将结果作为Dict。参考:Online Docs

示例代码:

for row in selectAA1:
    print(row._asdict())

0
投票

一种方法是:

Code:

def to_list_dict(data_elements):
    data = iter(data_elements)
    return [{d: next(data)} for d in data]

Test Code:

data = [3, 198, 3, 198, 3, 198, 3, 198, 3, 198]
print(to_list_dict(data))

Results:

[{3: 198}, {3: 198}, {3: 198}, {3: 198}, {3: 198}]
© www.soinside.com 2019 - 2024. All rights reserved.