Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fill nested dict when you only have a list of key, value for the final layers?

I have a nested dict of the folling form:

dict1 = {layer1: {layer2: {layer3: {a:None, b:None, c:None}}, {d:None, e:None}}}

And a flat dict with only the values in the final layer:

dict2 = {a:1, b:2, c:3, d:4, e:5}

My expected output after filling the values in the first dict would be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

dict_out = {layer1: {layer2: {layer3: {a:1, b:2, c:3}}, {d:4, e:5}}}

How should I approach this?

>Solution :

I hope I’ve understood your question correctly. You can use recursion to replace the values of keys in-place:

dct = {
    "layer1": {
        "layer2": {"layer3": {"a": 0, "b": 0, "c": 0}},
        "layer4": {"d": 0, "e": 0},
    }
}

dct2 = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}


def replace(d):
    if isinstance(d, dict):
        for k in d & dct2.keys():
            d[k] = dct2[k]

        for k in d - dct2.keys():
            replace(d[k])

    elif isinstance(d, list):
        for i in d:
            replace(i)


replace(dct)
print(dct)

Prints:

{
    "layer1": {
        "layer2": {"layer3": {"a": 1, "b": 2, "c": 3}},
        "layer4": {"d": 4, "e": 5},
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading