Count
In [1]:
#Counting Integers in a List
ages = [23, 45, 23, 34, 45, 23, 34, 45, 23]
count_23 = ages.count(23)
print(f'Age 23 appears {count_23} times.')
Age 23 appears 4 times.
In [2]:
#Counting Strings in a List
conditions = ['diabetes', 'hypertension', 'diabetes', 'asthma', 'hypertension', 'diabetes']
count_diabetes = conditions.count('diabetes')
print(f'Diabetes appears {count_diabetes} times.')
Diabetes appears 3 times.
In [3]:
#Counting Items in a Dictionary
patients = {
'patient_1': {'age': 23, 'condition': 'diabetes'},
'patient_2': {'age': 45, 'condition': 'hypertension'},
'patient_3': {'age': 34, 'condition': 'asthma'}
}
num_patients = len(patients)
print(f'There are {num_patients} patients in the record.')
There are 3 patients in the record.
In [4]:
from collections import Counter
import pprint
#Using Healthcare Data
patient_records = [
{'id': 1, 'age': 23, 'condition': 'diabetes'},
{'id': 2, 'age': 45, 'condition': 'hypertension'},
{'id': 3, 'age': 23, 'condition': 'asthma'},
{'id': 4, 'age': 34, 'condition': 'diabetes'},
{'id': 5, 'age': 45, 'condition': 'hypertension'}
]
conditions = [record['condition'] for record in patient_records]
condition_counts = Counter(conditions)
pprint.pp(f'Condition counts: {condition_counts}')
"Condition counts: Counter({'diabetes': 2, 'hypertension': 2, 'asthma': 1})"
