Python - Converting Arrays to Dict Hierarchy

We are talking about converting different data arrays into Python dictionaries.

Python - Converting Arrays to Dict Hierarchy
Photo by Markus Spiske / Unsplash

Here is an example of converting a Set into a Dict Hierarchy

import json

dataset = {"root", "sport", "football"}

datadict = dict()

for key in reversed(dataset):
    datadict = {key: datadict}

print(json.dumps(datadict, indent=4))

Output:

{
    "root": {
        "sport": {
            "football": {}
        }
    }
}

Subscribe to Devtooler

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe