0

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?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • Does this answer your question? [Update value of a nested dictionary of varying depth](https://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth) – Tomerikoo Oct 19 '21 at 10:38

1 Answers1

0

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

QuantumMecha
  • 1,514
  • 3
  • 22
  • If I do that my 'proxies': [{'addr': None, 'port': 5060}] - port is missing here? – ankur katiyar Oct 19 '21 at 10:20
  • 1
    You need also `new_dict['account']`. You want to update the "account" inner dict. So `old_dict['account'].update(new_dict['account'])` – Tomerikoo Oct 19 '21 at 10:21
  • I did that and you can see on your own that port will be missing if you try that out. – ankur katiyar Oct 19 '21 at 10:22
  • Yes, port is missing for the same reason. You will need a recursive solution if you want to update it like that. Try this page: https://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth – QuantumMecha Oct 19 '21 at 10:24