简体   繁体   中英

How to update the nested dictionary in Python?

I have a dictionary called old_dict , this has a template of entire required fields. I want it to get updated with the selective fields I have received. Why is that dictionary update method doesn't work here? Next, what is the correct way to update this? Do I need to loop around and check for each key and value and then check whether value is itself has a key and value. If so then keep iterating. What is the way to do so? I am looking for simplicity rather than a recursion solution.

Here is my current code:

old_dict = {'account': {'user': None, 'displayName': None, 'domain': '', 'dnsSrv': False, 'proxies': [{'addr': None, 'port': 5060}], 'vendor': 2, 'auth': {'user': None, 'passwd': None}, 'transport': 2, 'regInterval': 3600, 'avpfInterval': 3, 'sipsUri': False, 'avpf': False, 'reqRegister': True, 'pubPresenceInfo': False}}
print(old_dict)

new_dict = {'account': {'user': '007', 'dnsSrv': True, 'proxies': [{'addr': '10.10.10.201'}], 'pubPresenceInfo': False}}
print(new_dict)

old_dict.update(new_dict)
print("updated data")
print(old_dict)

I can see that displayName, domain and other fields are gone now. It has simply replaced account key with updated account key. How to tell Python to update individual items there?

old_dict is a separate dictionary to old_dict['account']

In this case, you are completely overwriting the old_dict['account'] dict object with a new dict object. If you want to update the existing one, you need to update that object itself:

old_dict['account'].update(new_dict['account'])

Thanks @Tomerikoo for the fix for proxies

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM