python - 在 python 中搜索字典列表

标签 python list dictionary

<分区>

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

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

我想查找是否有字典

字典[“stringa”]==“ABC”。如果是,则返回相应的字典。 我使用了函数“any”

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

但它只是给出 True/False。如何获取对应的字典。

最佳答案

使用next():

d = next((d for d in Mylist if d['Stringa'] == 'ABC'), None)
if d is not None: # found
    print(d)

参见 Python: find first element in a sequence that matches a predicate .

关于python - 在 python 中搜索字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26447309/

相关文章:

python - 将 24 小时日期/时间转换为 12 小时格式,反之亦然

python - 如何将列表中的元素乘以列表中相同的另一个元素,然后检查答案是否在另一个列表中?

php - Python 将文件行分成列表以发送到 MySQL

python - 如何从 2D 列表形成 2D 字典?

c# - C#中唯一的字符串集

Python Selenium 2.39 和 Firefox 26

python - 如何将多项式变换应用于 scikit 学习中的特征子集

python - while 循环阻塞异步任务

list - SharePoint 列表数据源出现 HTTP 401 "Unauthorized"错误

python - 字典python中的第二个最大值