Skip to content

Converting a dicom dataset to a standard python dictionary #1673

Answered by scaramallion
TariqAHassan asked this question in Q&A
Discussion options

You must be logged in to vote

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 elem.name or elem.keyword instead of elem.tag, however these may not be unique if there are private data elements.

Replies: 7 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by mrbean-bremen
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
4 participants
Converted from issue

This discussion was converted from issue #319 on August 17, 2022 19:32.