Search code examples
pythonpython-3.xfor-looppydicom

Defining variables in a loop based on a dictionary


I am converting DICOMs to PNGs with Python 3.x and Pydicom. There are occasional errors when reading DICOM header tags, causing the script to crash. Until now, I worked around it by using exceptions like below:

try: studyd = ds.StudyDate
except: studyd = ''
pass
...

This repetitive approach lengthens the code.

Unfortunately, I fail optimizing the code by defining a dictionary containing the Pydicom header and the target variable and looping through it. How could I do this with something like:

ds = pydicom.dcmread()
tags = { 'StudyDate': 'studyd', 'Modality': 'modal', 'PatientName': 'patname', etc.}
for key, val in tags.items():
...

Solution

  • Try this:

    ds = pydicom.dcmread()
    tags = { 'StudyDate': 'studyd', 'Modality': 'modal', 'PatientName': 'patname', etc.}
    header_dict = dict()
    for key, val in tags.items():
        header_dict[val] = getattr(ds, key)
    print(header_dict)
    

    Using the getattr to get the header value and storing it in a dict against the specified name