Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What does <= operator do with dict items

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading