【问题标题】:Storing values in tuples instead of dictionaries将值存储在元组而不是字典中
【发布时间】: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


【解决方案1】:

考虑在您的get_data 函数中使用collections.namedtuple

你可以这样声明:

CompanyData = collections.namedtuple('CompanyData', 'identity, closing_date, owner_identity')

然后您可以像这样创建一个:

data = CompanyData(cursor.fetchone())
return data

然后像这样访问它:

for company in options["databases"]["data"]:
    do_something_with(company.identity, company.owner_identity)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多