Kaow
Kaow

Reputation: 563

How to check if two value of dictionaries exist within the same index?

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

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

And I want to check if 'Alice' and 'Jack' or 'Bob' and 'Mike' is already exist in lists.

Upvotes: 0

Views: 71

Answers (3)

Nouman
Nouman

Reputation: 7303

Try this code:

values = [list(i.values()) for i in lists]
if ['Alice', 'Jack'] in values or ['Bob', 'Mike'] in values:
    print("All of them are there")

If you want the indexes:

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

Upvotes: 1

Óscar López
Óscar López

Reputation: 236004

Here's a solution that actually works:

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')

Upvotes: 1

Brandon
Brandon

Reputation: 31

for key, value in lists.items():
  if key == 'Alice' and value == 'Jack':
    return true

is that what your looking for? obviously would add another if clause to check if your other condition is met.

Upvotes: 0

Related Questions