Home > Software design >  adding values to objects in dictionary
adding values to objects in dictionary

Time:09-22

I want to add the following to each object in a dictionary. My dictionary looks like this:

{'Niveau1Obj1': {'Niveau2Obj1': {'Niveau3Obj1': {}}}}

For each object I want to add the following value:

{'type':'object'}

So the final outcome should look something like this:

{'Niveau1Obj1': {'type': 'object'}, 'Niveau2Obj1': {'type': 'object'}, 'Niveau3Obj1': {'type': 'object'}}

My code doesn't result in the desired outcome. The code is:

objects = {'Niveau1Obj1': {'Niveau2Obj1': {'Niveau3Obj1': {}}}}

for key, obj in objects.items():
    objects[key].setdefault(key, {}).update({'type':'object'})

It only adds the {'type':'object'} only to the last part of the dictionary. What am I doing wrong?

CodePudding user response:

Try a recursion:

dct = {"Niveau1Obj1": {"Niveau2Obj1": {"Niveau3Obj1": {}}}}


def get_keys(d):
    if isinstance(d, dict):
        for k in d:
            yield k
            yield from get_keys(d[k])


out = {k: {"type": "object"} for k in get_keys(dct)}
print(out)

Prints:

{
    "Niveau1Obj1": {"type": "object"},
    "Niveau2Obj1": {"type": "object"},
    "Niveau3Obj1": {"type": "object"},
}
  • Related