Skip to content
Advertisement

explode dictionary keys in a list

I want to explode the keys in a Python dict such that if I have as input:

d = {"first": 
        {"second_a": 3, "second_b": 4},
     "another": 2,
     "anotherone": {"third_a": {"last": 3}}
     }

I will get as output a list of the exploded keys:

["first.second_a",
"first.second_b",
"another",
"anotherone.third_a.last"
]

Do you know any utility function that does this?

Thank you!

Advertisement

Answer

If your dictionary contains only nested dictionaries you can do for example:

d = {
    "first": {"second_a": 3, "second_b": 4},
    "another": 2,
    "anotherone": {"third_a": {"last": 3}},
}


def flatten(d, prefix=""):
    for k, v in d.items():
        if isinstance(v, dict):
            yield from flatten(v, prefix + "." + k)
        else:
            yield (prefix + "." + k).strip(".")


print(list(flatten(d)))

Prints:

['first.second_a', 
 'first.second_b', 
 'another', 
 'anotherone.third_a.last']
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement