Search code examples
pythondictionarygetkey

Python - getting keys AND subkeys from nested dictionary


I've got a piece of JSON file, and since JSON is a dict, I want to get keys and subkeys from it.

JSON Code:

{
    "Image": {
        "URL / Path": "",
        "Max_Width": 300
    },
    "Font": {
...

What I want to achieve: ["Image", "Url / Path", "Max_Width", "Font", ..."]

What I have currently: ["Image", "Font", ...]. I've used l=[y for y in __import__('json').load(open(r'FilePath', 'r')).keys()];l for that.

Please help.


Solution

  • If you know the depth of a dictionary, you can just do something like this:

    data = {
            "Image": {
                "URL / Path": "",
                "Max_Width": 300
            },
            "Font": {}
    }
    all_keys = []
    for k in data:
        all_keys.append(k)
        for k1 in data[k]:
            all_keys.append(k1)
    

    This goes down to the second level, iterates through each key, and adds it to the result. However, if you have multiple (and variable amounts) of levels in your JSON, then you'll have to use recursion to get all the keys.