【问题标题】:Best method for repeated searches on large list of dicts重复搜索大量字典的最佳方法
【发布时间】:2013-08-17 03:24:59
【问题描述】:

假设我有一个函数,它从 postgres 数据库返回 1000 条记录作为 dicts 列表,看起来像这样(但要大得多):

[ {"thing_id" : 245, "thing_title" : "Thing title", "thing_url": "thing-url"},
  {"thing_id" : 459, "thing_title" : "Thing title II", "thing_url": "thing-url/2"}]

我有一个过程,需要根据给定的唯一 thing_id 在此列表中进行大约 600 次单独搜索以找到正确的字典。与其每次都遍历整个列表,不如创建一个字典的字典,让每个字典的 thing_id 成为一个键,这样不是更有效吗:

{245 : {"thing_id" : 245, "thing_title" : "Thing title", "thing_url": "thing-url"},
 459 : {"thing_id" : 459, "thing_title" : "Thing title II", "thing_url": "thing-url/2"}}

如果是这样,有没有首选的方法?显然我可以通过遍历列表来构建字典。但想知道是否有任何内置方法。如果不是,那么解决此问题的首选方法是什么?另外,有没有比我在这里提出的更好的方法从同一大记录集中重复检索数据,请告诉我。

更新:最终使用字典理解:

data = {row["thing_id"]: row for row in rows}

其中 rows 是我使用 psycopg2.extras.DictCursor 进行的 db 查询的结果。构建字典足够快,查找速度非常快。

【问题讨论】:

  • 你的预期输出是什么?
  • 我的预期输出是一个字符串,它连接了字典中的各种内容。由于我主要关心的是在相同的数据集和不同的用例中重复查找,因此我故意不强调我对数据所做的事情。基本上我想根据他们的thing_ids尽可能高效地返回我需要的字典。
  • 那个字符串到底是什么?你能给出你预期输出的样本吗?这将帮助我和其他人为您提供适合您需求的解决方案。
  • 假设我的输入是一个thing_id,我的输出是一个thing_url。我想要从同一个字典列表中进行大约 600 次这种检索的最快方法。我有一个thing_id,我想得到thing_id 所在的字典。

标签: python postgresql dictionary


【解决方案1】:

您可以使用 pandas DataFrame 结构进行多列索引:

>>> result = [
        {"thing_id" : 245, "thing_title" : "Thing title", "thing_url": "thing-url"},
        {"thing_id" : 459, "thing_title" : "Thing title II", "thing_url": "thing-url/2"}
    ]
>>> df = pd.DataFrame(result)
>>> df.set_index('thing_id', inplace=True)
>>> df.sort_index(inplace=True)
>>> df
             thing_title    thing_url
thing_id                             
245          Thing title    thing-url
459       Thing title II  thing-url/2
>>> df.loc[459, 'thing_title']
'Thing title II'

【讨论】:

  • 嗯,希望不必安装任何东西。
  • 这只是一个建议,因为它针对大型表格数据集进行了高度优化,您说:“另外,如果有比我建议的更好的方法从同一大记录集中重复检索数据在这里,请告诉我。”
  • 谢谢。如果我没有找到符合我要求的内置内容,我会检查一下。
  • 如果您决定使用它,它具有直接从数据库加载数据的优化版本,因此您不必重新排列它:df = pd.io.sql.read_sql('SELECT ... FROM ...', db_connection)
  • 嗯,太诱人了。
【解决方案2】:
a = [ {"thing_id" : 245, "thing_title" : "Thing title", "thing_url": "thing-url"}, {"thing_id" : 459, "thing_title" : "Thing title II", "thing_url": "thing-url/2"}]
c = [b.values()[1] for b in a]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-15
    相关资源
    最近更新 更多