BML91
BML91

Reputation: 3180

Pythonic way to create dictionary from bottom level of nested dictionary

I have a dictionary which contains nested dictionaries, like this:

example_dict = {
                "test1": "string here",
                "test2": "another string",
                "test3": {
                        "test4": 25,
                        "test5": {
                                  "test7": "very nested."
                        },
                        "test6": "yep, another string"
                },
}

Assuming all keys nested within are unique, is there a Pythonic way to take this dictionary and obtain a 'bottom' level of keys and values?

By this I mean going recursive into the dictionary and obtaining all key:value pairs where the value isn't a dictionary (but still capturing key:value pairs within that fulfil the critera)? So for the above the following would be returned:

resulting_dict = {
                "test1": "string here",
                "test2": "another string",
                "test4": 25,
                "test7": "very nested.",
                "test6": "yep, another string"
}

Upvotes: 1

Views: 1155

Answers (1)

Wolph
Wolph

Reputation: 80031

With a bit of recursion it's fairly simple to do:

example_dict = {
    "test1": "string here",
    "test2": "another string",
    "test3": {
        "test4": 25,
        "test5": {
            "test7": "very nested."
        },
        "test6": "yep, another string"
    },
}


def flatten(dictionary):
    output = dict()
    for k, v in dictionary.items():
        if isinstance(v, dict):
            output.update(flatten(v))
        else:
            output[k] = v

    return output

resulting_dict = flatten(example_dict)

Upvotes: 5

Related Questions