kubinka0505
kubinka0505

Reputation: 193

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.

Upvotes: 1

Views: 1779

Answers (2)

abe
abe

Reputation: 987

The function below returns all of the keys in a dict dct regardless of the depth:

def accumulate_keys(dct): # returns all the keys
    key_list = []
    def accumulate_keys_recursive(dct): # will accumulate keys in key_list
        for key in dct.keys():
            if isinstance(dct[key], dict):
                accumulate_keys_recursive(dct[key])
            else:
                key_list.append(key)
    accumulate_keys_recursive(dct)
    return key_list
print(accumulate_keys(dct))

Upvotes: 1

Kevin Sheng
Kevin Sheng

Reputation: 421

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.

Upvotes: 1

Related Questions