Python check if item is in dictionary items

51 Views Asked by At

Is it possible to check in python if an item is in a dictionary of items in a way like below:

for x in rows:
    print(x.items())
    for item in seq.items():
        print(item)
        if item in x.items():
            print("got it")
Rows = [{'name': 'Alice', 'AGATC': '2', 'AATG': '8', 'TATC': '3'},
        {'name': 'Bob', 'AGATC': '4', 'AATG': '1', 'TATC': '5'},
        {'name': 'Charlie', 'AGATC': '3', 'AATG': '2', 'TATC': '5'}]

Seq = {'AGATC': 4, 'AATG': 1, 'TATC': 5}

I know that I can check if value exist but I want check if whole item exists. It will be an easier way to do this.

1

There are 1 best solutions below

2
Mantas Kandratavičius On

Assuming you just want to loop through the rows and then loop through the items that you're looking for and check if any of those items are in a row... yes, that is very possible:

rows = [{'name': 'Alice', 'AGATC': '2', 'AATG': '8', 'TATC': '3'},
        {'name': 'Bob', 'AGATC': '4', 'AATG': '1', 'TATC': '5'},
        {'name': 'Charlie', 'AGATC': '3', 'AATG': '2', 'TATC': '5'}]

seq = {'AGATC': '4', 'AATG': '1', 'TATC': '5'}

for row in rows:
    if any(row.get(key) == value for key, value in seq.items()):
        print("Got it")

This way you're picking a row and checking if any of the items from seq can be found in the row. The finding itself checks whether the whole item exists, just like you want, by calling row.get(key) first (and checking if they key exists in the first place) and then by comparing it to the value you want it to be equal.


We're lucky that .get(key[, default])

Return[s] the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

as such you don't need to worry about crashing when comparing values of non-existent keys.

Instead of any(), you could also keep your 2nd loop and know exactly which item was found if you care about that information.