2

I have two dictionaries, the first is what the default values of the second one should fall back to if they are not present or not defined, and it is somewhat like this:

default_dict = {
    'lorem': {
        'foo': 'white',
        'bar': 'black',
    },
    'ipsum': {
        'xyz': '',
        'abc': {},
        'qwe': {}

    }
}

And the second looks like this:

custom_dict = {
    'lorem': {
        'bar': 'blue',
    },
    'ipsum': {
        'xyz': 'apple',
        'qwe': { 'one': 'strawberry' }

    }
}

Is there any way I can "update" from the default_dict with the values from the custom_dict?

The desired result would look something like this:

custom_dict = {
    'lorem': {
        'foo': 'white',
        'bar': 'blue',
    },
    'ipsum': {
        'xyz': 'apple',
        'abc': {},
        'qwe': { 'one': 'strawberry' }

    }
}

I've tried doing default_dict.update(custom_dict) and then custom_dict = default_dict, but as you can imagine I'm just getting custom_dict back untouched... So the keys of default_dict are getting removed when it is updated.

C1N14
  • 111
  • 10

2 Answers2

4

Use:

d={a:b for k,v in custom_dict.items() for a,b in v.items()}
print({k:{a:d.get(a,b) for a,b in v.items()} for k,v in default_dict.items()})

A dictionary comprehension + a nested dictionary comprehension would work.

Output:

{'lorem': {'foo': 'white', 'bar': 'blue'}, 'ipsum': {'xyz': 'apple', 'abc': {}, 'qwe': {'one': 'strawberry'}}}
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
1

if the structure of your dictionaries are always like above so the following code works fine:

for item in default_dict:
    for value in default_dict[item].keys():
        if value not in custom_dict[item].keys():
            custom_dict[item].update({value: default_dict[item][value]})

good luck

Arashsyh
  • 609
  • 1
  • 10
  • 16