在字典列表中搜索 Python 字典值的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1580270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the best way to search for a Python dictionary value in a list of dictionaries?
提问by Thierry Lam
I have the following data structure:
我有以下数据结构:
data = [
{'site': 'Stackoverflow', 'id': 1},
{'site': 'Superuser', 'id': 2},
{'site': 'Serverfault', 'id': 3}
]
I want to search the above list to see if it has any site with a specific value. For instance, search the above to see if the list contain a dictionary with site = 'Superuser' and return True/False. I can do the above the usual way of looping over each item and comparing them. Is there an alternative way to achieve a search?
我想搜索上面的列表,看看它是否有任何具有特定值的站点。例如,搜索上面的内容以查看列表是否包含带有 site = 'Superuser' 的字典并返回 True/False。我可以用循环遍历每个项目并比较它们的常用方法执行上述操作。有没有其他方法来实现搜索?
回答by Luká? Lalinsky
any(d['site'] == 'Superuser' for d in data)
回答by avguchenko
filter( lambda x: x['site']=='Superuser', data )
回答by S.Lott
Lists absolutely require loops. That's what lists are for.
列表绝对需要循环。这就是列表的用途。
To avoid looping you have to avoid lists.
为了避免循环,您必须避免使用列表。
You want dictionaries of search keys and objects.
您需要搜索键和对象的字典。
sites = dict( (d['site'],d) for d in data )
ids = dict( (d['id'],d] for d in data )
Now you can find the item associated with 'Superuser' with sites["Superuser"]
using a hashed lookup instead of a loop.
现在,您可以sites["Superuser"]
使用散列查找而不是循环来找到与“超级用户”关联的项目。
回答by Berry
I'm not sure of the python syntax, but it might work for you this way. While building your primary data structure, also build a parallel one that's a hash or associative array keyed on the site name; then to see if a given site exists you attempt a lookup in the hash with the site name. If it succeeds, you know there's a record in your data structure for that site and you've done it in the time of the hash lookup (likely O(1) or O(log2(n)) depending on the hash technique) instead of the O(n/2) of the list traversal.
我不确定 python 语法,但它可能对你有用。在构建您的主要数据结构的同时,还要构建一个并行的,它是一个以站点名称为键的散列或关联数组;然后要查看给定站点是否存在,您尝试使用站点名称在哈希中查找。如果它成功,您就知道该站点的数据结构中有一条记录,并且您已经在哈希查找时完成了它(可能是 O(1) 或 O(log2(n)),具体取决于哈希技术)列表遍历的 O(n/2)。
(updated while writing: this is pretty much what S.Lott posted)
(在写作时更新:这几乎就是 S.Lott 发布的内容)