gpt4 book ai didi

python - 当我不传递任何参数时,如何从 "dict_factory(cursor, row)"自动调用 "dict_factory"?

转载 作者:行者123 更新时间:2023-12-01 01:30:35 25 4
gpt4 key购买 nike

我对 python 开发非常陌生,在理解一个示例中使用的一种方法时遇到了困难,该方法是:

def dict_factory(cursor, row):

d={}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]

return d

并且它是从以下位置调用的:

conn = sqlite3.connect("books.db")
conn.row_factory = dict_factory
cur = conn.cursor()

现在有两个问题:

  1. 如何在不带参数的情况下从 dict_factory 调用 dict_factory(cursor, col)?

  2. dict_factory() 实际上是如何工作的?枚举是否将数据库分解为(c0,r0),(c0,r1)等格式?

dict_factory转换后的DB为:

[
{
"author": "Ann Leckie ",
"first_sentence": "The body lay naked and facedown, a deathly gray, spatters of blood staining the snow around it.",
"id": null,
"published": 2014,
"title": "Ancillary Justice"
},
{
"author": "John Scalzi",
"first_sentence": "From the top of the large boulder he sat on, Ensign Tom Davis looked across the expanse of the cave, toward Captain Lucius Abernathy, Science Officer Q\u2019eeng and Chief Engineer Paul West perched on a second, larger boulder, and thought, Well, this sucks.",
"id": null,
"published": 2013,
"title": "Redshirts"
}
]

最佳答案

  1. 在您显示的代码中,未调用 dict_factoryconn.row_factory = dict_factory 只是将该函数分配给属性 row_factory。这意味着您只是告诉数据库连接以哪种方式处理行(作为字典)。
  2. enumerate通过元素的索引来增强“正常”迭代(它返回元组 (index, element))。如果您执行 for col incursor.description: ,则 col 仅保存每列的名称。执行 for idx, col in enumerate(cursor.description): 会提供元组,其中第一个元素是迭代索引(从 0 开始),即 (0, col0), (1, col1), ...。现在,函数 dict_factoryrow 转换为 dict。它通过迭代各个列并向字典添加键值对 col_name: row_value_for_that_column 来实现此目的。

关于python - 当我不传递任何参数时,如何从 "dict_factory(cursor, row)"自动调用 "dict_factory"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52912374/

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