0

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():
...
  • Do you really need to define variables like that? Can't you use a dictionary to store the values instead? – rdas Apr 12 '20 at 12:51
  • I would prefer a dictionary. Would like to make a loop that sets the "val" of my dictionary as variable name and the ds.DICOMTAG as its value. – Sebastian Tschauner Apr 12 '20 at 12:59

1 Answers1

0

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

rdas
  • 20,604
  • 6
  • 33
  • 46