如何检查同一索引内是否存在两个字典值?

时间:2019-08-08 18:56:39

标签: python list dictionary

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

lists = [
{"from":'Alice', "to":'Jack'},
{"from":'Bob', "to":'Mike'}
]

我想检查列表中是否已经存在'Alice' and 'Jack''Bob' and 'Mike'

3 个答案:

答案 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子句,以检查您的其他条件是否得到满足。