1

I'm trying to perform operations on a nested dictionary (data retrieved from a yaml file):

data = {'services': {'web': {'name': 'x'}}, 'networks': {'prod': 'value'}}

I'm trying to modify the above using the inputs like:

{'services.web.name': 'new'}

I converted the above to a list of indices ['services', 'web', 'name']. But I'm not able to/not sure how to perform the below operation in a loop:

data['services']['web']['name'] = new

That way I can modify dict the data. There are other values I plan to change in the above dictionary (it is extensive one) so I need a solution that works in cases where I have to change, EG:

data['services2']['web2']['networks']['local'].

Is there a easy way to do this? Any help is appreciated.

1 Answer 1

1

You may iterate over the keys while moving a reference:

data = {'networks': {'prod': 'value'}, 'services': {'web': {'name': 'x'}}}
modification = {'services.web.name': 'new'}

for key, value in modification.items():
    keyparts = key.split('.')
    to_modify = data
    for keypart in keyparts[:-1]:
        to_modify = to_modify[keypart]
    to_modify[keyparts[-1]] = value

print(data)

Giving:

{'networks': {'prod': 'value'}, 'services': {'web': {'name': 'new'}}}
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome. I was able to get it working with some modifications! Appreciate the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.