在python中搜索字典列表 [英] Search a list of dictionary in python

查看:2290
本文介绍了在python中搜索字典列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典列表,我想查找列表中是否存在一个值,如果该值存在,则返回字典. 例如

I have a list of dictionaries and I want to find if a value exits in the list and if it exists return the dictionary. For example

Mylist= [{'Stringa': "ABC",
          'Stringb': "DE",
          'val': 5},
             {'Stringa': "DEF",
          'Stringb': "GHI",
          'val': 6}]

我想看看是否有字典

dict ["stringa"] =="ABC".如果是,则返回相应的字典. 我使用了任何"功能

dict["stringa"]=="ABC". If yes return the corresponding dictionary. I used the function "any"

any(d['Stringa'] == 'ABC' for d in Mylist)

但是它只给出对/错.如何获得相应的字典.

but it just gives True/False. How can I get the corresponding dictionary.

推荐答案

any将仅检查可迭代项中的任何一项是否满足条件.它不能用于检索匹配的项目.

any will just check if any of the items in the iterable satisfy the condition or not. It cannot be used to retrieve matching items.

使用列表推导来获取匹配项的列表,像这样

Use a list comprehension to get the list of matched items, like this

matches = [d for d in Mylist if d['Stringa'] == 'ABC']

这将遍历字典列表,每当找到匹配项时,它将包括在结果列表中.然后,您可以使用列表中的索引来访问实际的词典,例如matches[0].

This will iterate through the list of dictionaries and whenever it finds a match, it will include that in the result list. And then you can access the actual dictionary with its index in the list, like matches[0].

或者,您可以使用生成器表达式,像这样

Alternatively, you can use a generator expression, like this

matches = (d for d in Mylist if d['Stringa'] == 'ABC')

您可以从列表中获得下一个匹配项,

and you can get the next matched item from the list, with

actual_dict = next(matches)

这将为您提供实际的字典.如果要获取下一个匹配项,则可以再次使用生成器表达式调用next.如果您想一次获取所有匹配项,以列表的形式,只需执行

This will give you the actual dictionary. If you want to get the next matched item, you can call next with the generator expression again. If you want to get all the matching items at once, as a list, you can simply do

list_of_matches = list(matches)

注意:如果没有其他要从生成器中检索的项目,则调用next()会引发异常.因此,您可以传递要返回的默认值.

Note: Calling next() will raise an exception, if there are no more items to be retrieved from the generator. So, you can pass a default value to be returned.

actual_dict = next(matches, None)

现在,如果发电机已耗尽,则actual_dict将为None.

Now, actual_dict will be None if the generator is exhausted.

这篇关于在python中搜索字典列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆