如何向已构建的嵌套字典中添加新元素?附构建代码
Hey there! Let's break down how to add new elements to your nested dictionary—whether you want to insert them while you're generating the dictionary via DICOM traversal or after the dictionary is already fully built.
1. Add elements during the DICOM traversal (as you build the dict)
Your existing loop structure is perfect for inserting new data directly from the DICOM files as you process them. Let's expand on your code to add more fields (like patient name, scan date, or any other DICOM tag you need):
import os import pydicom # Assuming you're using pydicom for DICOM file handling data_dict = {} new_path = "/your/target/path" # Replace with your actual folder path for folders in os.listdir(new_path): # Initialize the patient folder entry first data_dict[folders] = {} avp_folder_path = os.path.join(new_path, folders) for AVP in os.listdir(avp_folder_path): # Initialize the AVP sequence entry data_dict[folders][AVP] = {} dicom_folder_path = os.path.join(avp_folder_path, AVP) for files in os.listdir(dicom_folder_path): dicom_file = pydicom.read_file(os.path.join(dicom_folder_path, files)) # Keep your existing Age field data_dict[folders][AVP]['Age'] = dicom_file.PatientAge # Add NEW elements here—pull from DICOM tags or add custom values # Example 1: Add patient name (convert to string since DICOM names are special objects) data_dict[folders][AVP]['PatientName'] = str(dicom_file.PatientName) # Example 2: Add scan date from the DICOM metadata data_dict[folders][AVP]['StudyDate'] = dicom_file.StudyDate # Example 3: Add a custom label for the sequence data_dict[folders][AVP]['SequenceLabel'] = f"{AVP} Phase"
This way, you populate new fields in real-time as you process each DICOM file, avoiding extra work later.
2. Add elements after the dictionary is already built
If you need to append data to the existing dict (like adding a calculated value or a missing field), you can traverse the nested structure directly:
Option A: Add a field to every entry in the dict
Say you want to add a Modality field to all sequences:
# Traverse each patient folder (e.g., '023', '024') for patient_id in data_dict: # Traverse each AVP sequence under the patient for sequence_type in data_dict[patient_id]: # Add the new field with your desired value data_dict[patient_id][sequence_type]['Modality'] = 'CT' # Or add a calculated value, e.g., a fixed slice count data_dict[patient_id][sequence_type]['SliceCount'] = 128
Option B: Add a field to a specific entry
If you only need to update one specific patient/sequence:
# Add a 'SliceThickness' field to patient '023', sequence 'ARTERIAL' data_dict['023']['ARTERIAL']['SliceThickness'] = '1.5mm'
Option C: Add an entirely new sequence to a patient
If you need to insert a new AVP sequence (like 'DELAYED') that wasn't in your original folder structure:
# First check if the sequence doesn't exist to avoid overwriting if 'DELAYED' not in data_dict['023']: data_dict['023']['DELAYED'] = {} # Add fields to the new sequence data_dict['023']['DELAYED']['Age'] = '043Y' data_dict['023']['DELAYED']['Modality'] = 'CT' data_dict['023']['DELAYED']['StudyDate'] = '20240520'
Quick Note: Avoid KeyErrors
If you're unsure if a nested key exists (e.g., a patient might not have a certain sequence), check for existence first to prevent crashes:
# Safely add a field only if the patient and sequence exist if '025' in data_dict and 'VENOUS' in data_dict['025']: data_dict['025']['VENOUS']['NewField'] = 'CustomValue'
内容的提问来源于stack exchange,提问作者DecentMakeover

