我有一个Python字典列表,如下所示:
lists = [
{"from":'Alice', "to":'Jack'},
{"from":'Bob', "to":'Mike'}
]
我想检查列表中是否已经存在'Alice' and 'Jack'
或'Bob' and 'Mike'
。
答案 0 :(得分:1)
尝试以下代码:
values = [list(i.values()) for i in lists]
if ['Alice', 'Jack'] in values or ['Bob', 'Mike'] in values:
print("All of them are there")
如果需要索引:
>>> lists = [{"from":'Alice', "to":'Jack'}, {"from":'Bob', "to":'Mike'}]
>>> values = [list(i.values()) for i in lists]
>>> if ['Alice', 'Jack'] in values or ['Bob', 'Mike'] in values:
print("All of them are there")
All of them are there
>>> print(values.index(['Alice', 'Jack']))
0
>>> print(values.index(['Bob', 'Mike']))
1
>>>
答案 1 :(得分:1)
这是一个实际可行的解决方案:
names = set((pair['from'], pair['to']) for pair in lists)
if ('Alice', 'Jack') in names or ('Bob', 'Mike') in names:
print('the pair exists in the list')
答案 2 :(得分:0)
for key, value in lists.items():
if key == 'Alice' and value == 'Jack':
return true
这是您要找的东西吗?显然会添加另一个if子句,以检查您的其他条件是否得到满足。