Post

🏫 [CS50x 2025] 6 Python

🏫 [CS50x 2025] 6 Python

Check if a dict is a subset of another dict

Option 1: Do all keys & values in crime_gene appear in p?

1
2
if all(p.get(k) == v for k, v in crime_gene.items()):
    return True

This checks:

  • For every gene in crime_gene, does p have the same value?
  • It’s doing a field-by-field match - very forensics-style

Option 2: Check if crime_gene.items() is a subset of p.items()?

1
2
if crime_gene.items() <= p.items():
    return True

Example

1
2
3
4
5
6
7
8
9
10
crime_gene = {'AGATC': '2', 'AATG': '8', 'TATC': '3'}
p = {'name': 'Alice', 'AGATC': '2', 'AATG': '8', 'TATC': '3'}

# Both of these work:
if all(p.get(k) == v for k, v in crime_gene.items()):
    return True

# OR:
if crime_gene.items() <= p.items():
    return True

if all(p.get(k) == v for k, v in crime_gene.items()):

For every gene in crime_gene, check if p has the same key with the same value. If all of them match, return True, otherwise nope.

for k, v in crime_gene.items()

This part loops over every key: value pair in crime_gene. Think of it like:

1
for k, v in [('AGATC', '2'), ('AATG', '8'), ('TATC', '3')]:

So:

  • k = 'AGATC', v = '2'
  • k = 'AATG', v = '8'
  • …

p.get(k) == v

For each key in crime_gene, we’re checking:

Does p have this same key, and is the value the same?

p.get(k) is safer than p[k] because it won’t throw an error if the key doesn’t existβ€”it’ll return None.

So for example:

1
2
3
p.get('AGATC') == '2'  β†’ βœ…
p.get('AATG') == '8'   β†’ βœ…
p.get('TATC') == '3'   β†’ βœ…

all(...)

The all() function checks:

Are ALL these expressions True?

If even one is False, then all() returns False.

This post is licensed under CC BY 4.0 by the author.