检查字典列表中是否已经存在值?

编程入门 行业动态 更新时间:2024-10-12 20:28:27
本文介绍了检查字典列表中是否已经存在值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个Python字典列表,如下所示:

I've got a Python list of dictionaries, as follows:

a = [ {'main_color': 'red', 'second_color':'blue'}, {'main_color': 'yellow', 'second_color':'green'}, {'main_color': 'yellow', 'second_color':'blue'}, ]

我想检查列表中是否已存在具有特定键/值的字典,如下所示:

I'd like to check whether a dictionary with a particular key/value already exists in the list, as follows:

// is a dict with 'main_color'='red' in the list already? // if not: add item

推荐答案

这里是一种方法:

if not any(d['main_color'] == 'red' for d in a): # does not exist

括号中的部分是一个生成器表达式,对于具有要查找的键值对的每个词典,返回True,否则返回False.

The part in parentheses is a generator expression that returns True for each dictionary that has the key-value pair you are looking for, otherwise False.

如果密钥也可能丢失,则上面的代码可以为您提供KeyError.您可以使用get并提供默认值来解决此问题.

If the key could also be missing the above code can give you a KeyError. You can fix this by using get and providing a default value.

if not any(d.get('main_color', None) == 'red' for d in a): # does not exist

更多推荐

检查字典列表中是否已经存在值?

本文发布于:2023-11-28 18:28:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1643482.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典   列表中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!