Hướng dẫn python deep merge json
It depends slightly on what you want Solution 1If you simply want to replace all values by the new dictionary, you can use the following options:
This will result in:
Alternatively you can use
Which will lead to the same outcome, but will update Solution 2If you only want to update the specific key in the nesting, and leave all other values intact, you can do this using recursion. In
your example you are using
The above might be a bit harder to understand, but I will try to explain it. There are two methods, one which will merge two dictionaries and one that tries to merge two lists. Merging dictionariesIn order to merge the two dictionaries I go over all the keys and values of the update dictionary, because this will probably be the smaller of the two. The first block puts new keys in the original dictionary, this is updating values that weren't in the original dictionary at the start. The second block is updating the nested values. There I distinguish three cases:
Merging listsThis is a bit trickier than dictionaries, because lists do not have an order or keys that I can compare. Therefore I have to make a heavy assumption that the Since the
Resultusing:
The final result will be:
Note that in
contrast with the first solution the values LimitationsDue to the same length constraint, if you do not want to update an element in the list you have to pass the same element type, but empty. Example on how to ignore a list update: |