Home > Software design >  Fill Multiple empty values in python dictionary for particular key all over dictionary
Fill Multiple empty values in python dictionary for particular key all over dictionary

Time:10-11

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": ""}}

CodePudding user response:

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': ''}
}
  • Related