【发布时间】:2017-07-16 19:03:02
【问题描述】:
目前,我正在使用这样的脚本从 10.000 多个数据库中获取数据:
def get_data(cursor):
cursor.execute("SELECT * FROM COMPANIES")
identity, closing_date, owner_identity = cursor.fetchall()
return {
"identity": identity,
"closing_date": closing_date,
"owner_identity": owner_identity
}
def collect_databases_data(options):
options["databases"]["data"] = [
get_data(connection.cursor())
for connection in options["databases"].values()
]
return options
然后我遍历字典列表:
for data in options["databases"]["data"]:
# i do something here with identity, closing_date and owner_identity
我正在考虑更改脚本以返回元组,而不是字典:
def get_data(cursor):
cursor.execute("SELECT * FROM COMPANIES")
return cursor.fetchall()
def collect_databases_data(options):
options["databases"]["data"] = [
get_data(connection.cursor())
for connection in options["databases"].values()
]
return options
那么我可以:
for identity, closing_date, owner_identity in options["databases"]["data"]:
# I do something here with identity, closing_date and owner_identity
哪个会更快(有时我可以拥有 20.000 个字典),但没有解释就无法阅读。这被认为是一种不好的做法吗?我应该避免吗?我看到 Python 程序员喜欢列表和元组,但我还不知道他们是否也使用元组来存储数据。
【问题讨论】:
-
您是否尝试过使用 NamedTuple 来表示行?这应该比字典更轻,但仍嵌入描述。
标签: python dictionary tuples