Converting a dicom dataset to a standard python dictionary #1673
-
I have not been able to find an easy way to do this by reading the documentation or skimming the source code. To give a concrete example, I'd like to convert this example from the docs
to a dictionary something like this:
One solution looks something like this:
However, that's not particularly elegant. |
Beta Was this translation helpful? Give feedback.
Replies: 7 comments
-
Your example won't work for sequences. def dictify(ds):
"""Turn a pydicom Dataset into a dict with keys derived from the Element tags.
Parameters
----------
ds : pydicom.dataset.Dataset
The Dataset to dictify
Returns
-------
output : dict
"""
output = dict()
for elem in ds:
if elem.VR != 'SQ':
output[elem.tag] = elem.value
else:
output[elem.tag] = [dictify(item) for item in elem]
return output You could also use |
Beta Was this translation helpful? Give feedback.
-
@scaramallion Thank you very much for the help.
That said, I think that a function like the one you have written would make a very nice addition to the library. |
Beta Was this translation helpful? Give feedback.
-
I've used the following to convert a dataset to a dict (for storing as JSON) if it's any help. The def dicom_dataset_to_dict(dicom_header):
dicom_dict = {}
repr(dicom_header)
for dicom_value in dicom_header.values():
if dicom_value.tag == (0x7fe0, 0x0010):
# discard pixel data
continue
if type(dicom_value.value) == dicom.dataset.Dataset:
dicom_dict[dicom_value.tag] = dicom_dataset_to_dict(dicom_value.value)
else:
v = _convert_value(dicom_value.value)
dicom_dict[dicom_value.tag] = v
return dicom_dict
def _sanitise_unicode(s):
return s.replace(u"\u0000", "").strip()
def _convert_value(v):
t = type(v)
if t in (list, int, float):
cv = v
elif t == str:
cv = _sanitise_unicode(v)
elif t == bytes:
s = v.decode('ascii', 'replace')
cv = _sanitise_unicode(s)
elif t == dicom.valuerep.DSfloat:
cv = float(v)
elif t == dicom.valuerep.IS:
cv = int(v)
elif t == dicom.valuerep.PersonName3:
cv = str(v)
else:
cv = repr(v)
return cv |
Beta Was this translation helpful? Give feedback.
-
Ah yeah, sorry, |
Beta Was this translation helpful? Give feedback.
-
Thinking about it a bit more, you're better off using |
Beta Was this translation helpful? Give feedback.
-
Thank you very much @scaramallion and @jstutters. |
Beta Was this translation helpful? Give feedback.
-
I know this is super old, but FWIW @scaramallion's answer was just what I needed. I ended up tweaking it though to use the element name and also str() the value for full JSON compatibility (
|
Beta Was this translation helpful? Give feedback.
Your example won't work for sequences.
You could also use
elem.name
orelem.keyword
instead ofelem.tag
, however these may not be unique if there are private data elements.