Python:使用 SQL 从 table 作为字典检索列

Python: retrieve column from a table as dictionary using SQL

我在我的 python 代码中使用 psycopg2 来做一个 从 postgres table.

中选择 column1,column2

我想将查询的 o/p 存储为字典,其中 column1 为键,column2 为值。有什么想法吗?

这可以使用 python 内置的 dict() 函数轻松完成。 在我的示例中,我假设结果存储在变量 sql_result 中,但您可以使用 SQL 结果将其更改为变量:

sql_result = [
    [1, "A"],
    [2, "B"],
    [3, "C"]
    ]

res = dict(sql_result)
print(res)