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

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

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

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

 // 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 

括号中的部分是一个生成器expression式,对于每个包含要查找的键值对的字典,返回True ,否则返回False


如果密钥也可能缺less上面的代码可以给你一个KeyError 。 你可以通过使用get和提供一个默认值来解决这个问题。

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

也许这有助于:

 a = [{ 'main_color': 'red', 'second_color':'blue'}, { 'main_color': 'yellow', 'second_color':'green'}, { 'main_color': 'yellow', 'second_color':'blue'}] def in_dictlist((key, value), my_dictlist): for this in my_dictlist: if this[key] == value: return this return {} print in_dictlist(('main_color','red'), a) print in_dictlist(('main_color','pink'), a) 

也许这些线上的function是你所追求的:

  def add_unique_to_dict_list(dict_list, key, value): for d in dict_list: if key in d: return d[key] dict_list.append({ key: value }) return value