π« [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
, doesp
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.