SetDefault
In [1]:
import pprint
In [2]:
# Patient records dictionary
patient_records = {
'P001': {'name': 'John Doe', 'age': 30, 'conditions': ['hypertension']},
'P002': {'name': 'Jane Smith', 'age': 25, 'conditions': ['diabetes']}
}
patient_id = 'P003'
patient_records.setdefault(patient_id, {'name': 'New Patient', 'age': 0, 'conditions': []})
pprint.pp(patient_records)
{'P001': {'name': 'John Doe', 'age': 30, 'conditions': ['hypertension']},
'P002': {'name': 'Jane Smith', 'age': 25, 'conditions': ['diabetes']},
'P003': {'name': 'New Patient', 'age': 0, 'conditions': []}}
In [3]:
# Adding a new condition to a patient's record
patient_id = 'P001'
new_condition = 'asthma'
print("current")
pprint.pp(patient_records)
patient_records.setdefault(patient_id, {}).setdefault('conditions', []).append(new_condition)
print("new")
pprint.pp(patient_records)
current
{'P001': {'name': 'John Doe', 'age': 30, 'conditions': ['hypertension']},
'P002': {'name': 'Jane Smith', 'age': 25, 'conditions': ['diabetes']},
'P003': {'name': 'New Patient', 'age': 0, 'conditions': []}}
new
{'P001': {'name': 'John Doe',
'age': 30,
'conditions': ['hypertension', 'asthma']},
'P002': {'name': 'Jane Smith', 'age': 25, 'conditions': ['diabetes']},
'P003': {'name': 'New Patient', 'age': 0, 'conditions': []}}
In [4]:
# Medication records dictionary
medication_records = {
'P001': {'medications': ['Aspirin']},
'P002': {'medications': ['Metformin']}
}
patient_id = 'P001'
new_medication = 'Lisinopril'
medication_records.setdefault(patient_id, {}).setdefault('medications', []).append(new_medication)
pprint.pp(medication_records)
{'P001': {'medications': ['Aspirin', 'Lisinopril']},
'P002': {'medications': ['Metformin']}}
