将值存储在元组中而不是字典中

时间:2017-02-26 02:50:29

标签: python dictionary tuples

目前,我使用如下脚本从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程序员喜欢列表和元组,但我还不知道他们是否也使用元组来存储数据。

1 个答案:

答案 0 :(得分:0)

考虑在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)