[英]Searching through a list of dictionaries to see if a key/value exists in any dictionary
so I have a list of dictionaries, ex: 所以我有一个字典清单,例如:
[{'title':'Green eggs and ham', 'author':'dr seuss'}, {'title':'matilda', 'author':'roald dahl'}]
What is the best way to search if outliers by malcolm gladwell exists in any of those dictionaries? 马尔科姆·格威尔威尔(Marcolm Gladwell)的离群值是否存在于任何这些词典中,这是搜索的最佳方法是什么?
I was thinking of brute force checking each title and author, but I feel like there's gotta be a better way. 我当时想用蛮力检查每个标题和作者,但我觉得必须有更好的方法。
If you need all key-value pairs to match, you can just use in
and have the list do the searching for you: 如果需要所有键值对匹配,则可以使用
in
并让列表为您搜索:
if {'title': 'outliers', 'author': 'malcolm gladwell'} in yourlist:
Otherwise, with no other indices, you'll have to 'manually' search the list. 否则,没有其他索引,则必须“手动”搜索列表。 You can use the
any
function with a generator expression to make the test efficient enough (eg stop searching when a match is found), plus dictionary view objects to test for subsets of key-value pairs: 您可以将
any
函数与生成器表达式一起使用,以使测试足够有效(例如,找到匹配项时停止搜索),以及字典视图对象以测试键值对的子集:
search = {'title': 'outliers', 'author': 'malcolm gladwell'}.viewitems()
if any(search <= d.viewitems() for d in yourlist):
would match even if dictionaries in yourlist
have more keys than just title
and author
. 即使
yourlist
字典yourlist
具有title
和author
键, yourlist
可以匹配的。
You can avoid full scans by using extra indices: 您可以通过使用额外的索引来避免完全扫描:
authors = {}
titles = {}
for d in yourlist:
authors.set_default(d['author'], []).append(d)
titles.set_default(d['title'], []).append(d)
creates extra mappings by specific keys in the dictionaries. 通过词典中的特定键创建额外的映射。 No you can test for individual elements:
不,您可以测试单个元素:
if any(d['title'] == 'outliers' for d in authors.get('malcolm gladwell', [])):
is a limited search just through all books by Malcolm Gladwell. 仅针对Malcolm Gladwell的所有书籍进行的有限搜索。
The titles
and authors
dictionaries map author and title strings to lists of the same dictionaries , shared with the yourlist
list. titles
和authors
字典将作者和标题字符串映射到与yourlist
列表共享的相同字典的列表。 However, adding or removing dictionaries from one such structure does require updating all structures. 但是,从一个这样的结构中添加或删除字典确实需要更新所有结构。 This is where a relational database comes in handy, as it is really good at keeping such indexes for you and will automatically keep these up-to-date.
这是关系数据库派上用场的地方,因为它非常擅长为您保留此类索引,并且会自动使它们保持最新状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.