gpt4 book ai didi

python - 记录python中等效的数据类型

转载 作者:行者123 更新时间:2023-12-04 10:37:15 24 4
gpt4 key购买 nike

我正在连接到 snowfalke 数据库并仅获取 1 条记录。该记录将有 21 列。在我使用连接在 python 中读取它们之后,它们返回一个元组对象。

我想使用名称访问元组对象的元素。

最好我想访问这些与数据库中列名同名的元组元素。

在 PL/SQL 中,我们有一种叫做记录类型的东西。并且可以通过名称访问记录中的元素

我如何在 python 中做到这一点?

伪代码例如:

tup_obj = connection.execute('select name, age, height, weight from table')

我想使用这样的名称访问元组对象,
tup_obj.name == 'Harish' ?

以上只是要求的一个例子。以下是我的用例具有相同结构的模拟数据:
print(type(tup_obj))
print(tup_obj)

<class 'tuple'>
(101010, 5, 1, 200, 'text', 'text', 'text', 'text', 18075, 'text', 'text', 'text', 37, 2, 57, 'Y', 'S', 'S', 'text', 123, 'text')

最佳答案

使用字典数据结构来存储和访问,如 tup_obj.name

columns = ['name', 'age', 'height', 'weight']
data = [('a', 20, 170, 80)] # This will be your select query results
out = [dict(zip(columns, x)) for x in data]

输出
[{'name': 'a', 'age': 20, 'height': 170, 'weight': 80}]

访问使用
out[0]['name'] # This will give string 'a'

编辑:

对于元组,直接使用
dict(zip(columns, data))

关于python - 记录python中等效的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60107228/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com