Home > Software engineering >  What does <= operator do with dict items
What does <= operator do with dict items

Time:12-06

I'm struggling with understanding how the <= operator works.

I have one list with one dictionary element (just one element) called result:

dict_items([('AGATC', '4'), ('AATG', '1'), ('TATC', '5')])

I also have list of dictionary elements (more than one) called data:

dict_items([('name', 'Alice'), ('AGATC', '2'), ('AATG', '8'), ('TATC', '3')])
dict_items([('name', 'Bob'), ('AGATC', '4'), ('AATG', '1'), ('TATC', '5')])
dict_items([('name', 'Charlie'), ('AGATC', '3'), ('AATG', '2'), ('TATC', '5')])

Code that is problematic is here:

# Check if any person in csv file matches output from dna_count
for row in data:
    if result.items() <= row.items():
        print(row["name"])

I understand that it checks if any row of data matches element of result, and if it does then it prints name from that row, but why operator == isn't working there and I need to use <=, and how does <= behave because in result there is no name key, does it skip name key?

CodePudding user response:

Keys views are set-like since their entries are unique and hashable. If all values are hashable, so that (key, value) pairs are unique and hashable, then the items view is also set-like. [..] For set-like views, all of the operations defined for the abstract base class collections.abc.Set are available (for example, ==, <, or ^).

https://docs.python.org/3/library/stdtypes.html#dict-views

So, you can use set comparison operators here, and result.items() <= row.items() tests if result.items() is a subset of row.items(). Subset means that it contains some items but not any other items.

Which is obviously what makes this comparison true:

dict_items([('AGATC', '4'), ('AATG', '1'), ('TATC', '5')])

dict_items([('name', 'Bob'), ('AGATC', '4'), ('AATG', '1'), ('TATC', '5')])

The first "set" here is a subset of the second, but it's not equal (because it's missing one item).

  • Related