Fill Multiple empty values in python dictionary for particular key all over dictionary

Question:

I have a dictionary as below.
Key id is present multiple times inside dictionary.I need to fill id value at all places in dicts in single line of code.
Currently I am writing multiple line of code to fill empty values.

dicts = {
    "abc": {
            "a":{"id": "", "id1":""},
            "b":{"id": "","hey":"1223"},
            "c":{"id": "","hello":"4564"}
          },
    "xyz": {
            "d":{"id": "","id1":"", "ijk":"water"}
            },
     "f":{"id": ""},
     "g":{"id1": ""}

}

id = 123
dicts['abc']['a']['id'] = id
dicts['abc']['b']['id'] = id
dicts['abc']['c']['id'] = id
dicts['xyz']['d']['id'] = id
dicts['f']['id'] = id
dicts

Output:

{'abc': {'a': {'id': 123,"id1":""},
  'b': {'id': 123, 'hey': '1223'},
  'c': {'id': 123, 'hello': '4564'}},
 'xyz': {'d': {'id': 123,id1:"", 'ijk': 'water'}},
 'f': {'id': 123}, "g":{"id1": ""}}
Asked By: Divyank

||

Answers:

You can solve it in place via simple recursive function, for example:

id = 123
dicts = {
    "abc": {
        "a": {"id": "", "id1": ""},
        "b": {"id": "", "hey": "1223"},
        "c": {"id": "", "hello": "4564"}
    },
    "xyz": {
        "d": {"id": "", "id1": "", "ijk": "water"}
    },
    "f": {"id": ""},
    "g": {"id1": ""}

}



def process(dicts):
    for k, v in dicts.items():
        if k == 'id' and not dicts[k]:
            dicts[k] = id
        if isinstance(v, dict):
            process(v)


process(dicts)
print(dicts)

Output:

{
    'abc': {'a': {'id': 123, 'id1': ''}, 
            'b': {'id': 123, 'hey': '1223'}, 
            'c': {'id': 123, 'hello': '4564'}}, 
    'xyz': {'d': {'id': 123, 'id1': '', 'ijk': 'water'}}, 
    'f': {'id': 123}, 'g': {'id1': ''}
}
Answered By: funnydman
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.