AP2*_*257 107 python dictionary list
我有一个Python字典列表,如下所示:
a = [
{'main_color': 'red', 'second_color':'blue'},
{'main_color': 'yellow', 'second_color':'green'},
{'main_color': 'yellow', 'second_color':'blue'},
]
Run Code Online (Sandbox Code Playgroud)
我想检查列表中是否已存在具有特定键/值的字典,如下所示:
// is a dict with 'main_color'='red' in the list already?
// if not: add item
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 227
这是一种方法:
if not any(d['main_color'] == 'red' for d in a):
# does not exist
Run Code Online (Sandbox Code Playgroud)
括号中的部分是一个生成器表达式,它返回True具有您要查找的键值对的每个字典,否则False.
如果密钥也可能丢失,上面的代码可以给你一个KeyError.您可以通过使用get并提供默认值来解决此问题.
if not any(d.get('main_color', None) == 'red' for d in a):
# does not exist
Run Code Online (Sandbox Code Playgroud)
基于@Mark Byers很好的答案,以及以下@Florent问题,只是为了表明它也适用于具有超过2个键的dic列表上的2个条件:
names = []
names.append({'first': 'Nil', 'last': 'Elliot', 'suffix': 'III'})
names.append({'first': 'Max', 'last': 'Sam', 'suffix': 'IX'})
names.append({'first': 'Anthony', 'last': 'Mark', 'suffix': 'IX'})
if not any(d['first'] == 'Anthony' and d['last'] == 'Mark' for d in names):
print('Not exists!')
else:
print('Exists!')
Run Code Online (Sandbox Code Playgroud)
结果:
Exists!
Run Code Online (Sandbox Code Playgroud)
也许这会有所帮助:
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)
Run Code Online (Sandbox Code Playgroud)
这是执行OP要求的另一种方法:
if not filter(lambda d: d['main_color'] == 'red', a):
print('Item does not exist')
Run Code Online (Sandbox Code Playgroud)
filter会将列表过滤到 OP 正在测试的项目。然后,条件if提出问题“如果该项目不存在”,则执行该块。