Home > Blockchain >  Python dictionary replace nested values
Python dictionary replace nested values

Time:01-22

I'd like to make specific changes to key values that are nested in a Python dictionary.

E.g.

my_dict = {"header": {"from": "/app/510112-0b0bf05b07dc5bb03fa414642e849a11/subscribe",
                                  "messageId": "ef6b8e50620ac768569f1f7abc6507a5", "method": "GET",
                                  "namespace": "Appliance.System.All", "payloadVersion": 1,
                                  "sign": "e48c24e510044d7e2d248c68ff2c10ca", "timestamp": 1601908439,
                                  "triggerSrc": "Android"}, "payload": {}}

and I want to change the value of "messageId" and "timestamp".

I found this post:- Python dictionary replace values, which has pretty much every solution needed.

My scenario is that I'd like to change nested values without having to use the for loop method of finding keys.

With that in mind I tried the update and merge options.

my_dict.update({'key1': 'value1', 'key2': 'value2'})
my_dict.update(key1='value1', key2='value2')
my_dict = my_dict | {'key1': 'value1', 'key2': 'value2'}
my_dict |= {'key1': 'value1', 'key2': 'value2'}

I tried the following:-

my_dict |= {'header':{'messageId':9}}
my_dict = json_dict | {'header':{'messageId':9}}
my_dict.update({'header':{'messageId':9}})
my_dict.update({"header":{"messageId":'a'}})

Unfortuantely although these all work correctly when working with an unnested dictionary, when I try these on my nested dictionary all the other keys and values in that prticualr part of the dictionary get removed, except for the ones I append/update or are outside that nesting.

>>> my_dict
{'header': {'messageId': 'a'}, 'payload': {}}

Is this as issue with updating nested dictionaries or have I made a mistake in my assumption on how to use these calls with a nested dictionary?

Thanks.

CodePudding user response:

If you want to change the value of a key in a dict that is nested within another dict, you can reference the nested dictionary's key like so to change the value:

my_dict["header"]["messageId"] = "updated messageId"
my_dict["header"]["timestamp"] = "updated timestamp"

print(my_dict)

Which keeps the rest of the entry intact and changes only the referenced keys.

  • Related