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

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

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

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

>Solution :

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