【问题标题】:Searching through a list of dictionaries to see if a key/value exists in any dictionary搜索字典列表以查看任何字典中是否存在键/值
【发布时间】:2014-07-06 16:31:17
【问题描述】:

所以我有一个字典列表, 例如:

[{'title':'Green eggs and ham', 'author':'dr seuss'}, {'title':'matilda', 'author':'roald dahl'}]

如果这些字典中存在 malcolmglad​​well 的异常值,最好的搜索方法是什么?

我正在考虑蛮力检查每个标题和作者,但我觉得必须有更好的方法。

【问题讨论】:

  • 列表是否以任何方式排序?
  • 你能改变结构吗? {author: {title: book, ...}, ...} 让它变得微不足道。
  • 您需要它们作为字典吗? set 的元组(标题,作者)可能会更快

标签: python list search dictionary


【解决方案1】:

如果您需要 所有 键值对来匹配,您可以使用 in 并让列表为您搜索:

if {'title': 'outliers', 'author': 'malcolm gladwell'} in yourlist:

否则,如果没有其他索引,您将不得不“手动”搜索列表。您可以将any function 与生成器表达式一起使用以使测试高效足够(例如,找到匹配时停止搜索),加上dictionary view objects 来测试键值对的子集:

search = {'title': 'outliers', 'author': 'malcolm gladwell'}.viewitems()
if any(search <= d.viewitems() for d in yourlist):

即使yourlist 中的字典具有比titleauthor 更多的键,也会匹配。

您可以通过使用额外的索引来避免完全扫描:

authors = {}
titles = {}
for d in yourlist:
    authors.set_default(d['author'], []).append(d)
    titles.set_default(d['title'], []).append(d)

通过字典中的特定键创建额外的映射。不,您可以测试单个元素:

if any(d['title'] == 'outliers' for d in authors.get('malcolm gladwell', [])):

仅通过 Malcolm Gladwell 的所有书籍进行有限搜索。

titlesauthors 字典将作者和标题字符串映射到相同字典的列表,与yourlist 列表共享。但是,从一个这样的结构中添加或删除字典确实需要更新所有结构。这就是关系数据库派上用场的地方,因为它非常擅长为您保留此类索引,并且会自动使这些索引保持最新。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-22
    • 1970-01-01
    • 2021-05-31
    相关资源
    最近更新 更多