Merge Two Dictionaries And Persist The Values Of First Dictionaries
Solution 1:
Do second.update(first)
. Any keys in both will have their value set to the value in first
and any keys that are in first
but not second
will be added to second
.
Solution 2:
Update()
will work, simply copy the second dict and apply the first one. So the value of the first will replace the second and not the reverse way.
first = {"phone": {"home": "(234) 442-4424"},"address":"xyz"}
second = {"phone": {"home": "(234) 442-5555","home1": "(234) 442-4424"},"address":{}}
# recursive deep update you can find here: http://stackoverflow.com/a/3233356/956660import collections
defupdate(d, u):
for k, v in u.iteritems():
ifisinstance(v, collections.Mapping):
r = update(d.get(k, {}), v)
d[k] = r
else:
d[k] = u[k]
return d
third = second.copy()
update(third, first)
print(third)
{'phone': {'home': '(234) 442-4424', 'home1': '(234) 442-4424'}, 'address': 'xyz'}
Solution 3:
If you want to just add the missing key/value pairs into the first dictionary, you can just add them to the first instead of creating a new dictionary.
first = {}
second = {}
for key in second.keys():
if key not in first:
first[key] = second[key]
Edit: your comment "it wont work with multilevel dictionary"
Actually, it will..technically speaking.
first = {"Person1" : {"Age": "26", "Name": "Person1", "Phone number": "XXXXXX"}}
second = {"Person1": {"Interests": "fishing"}, "Person2": {"Age": "26", "Name": "Person2", "Phone number": "XXXXXX"}}
In this case, the first
dict will get the Person2
object, but will not change the Person1
object, as it is already there!
Solution 4:
Assuming your dictionnaries have following structure:
- each element is a dictionnary
- values are either plain strings or dictionnaries
Assuming that the requirement is:
- if a key exist only in one of the 2 elements to merge, keep its value
- if a key exists in both elements:
- if the value in first element is a plain string, keep its value
- if the value in first element is a dict and the value in second is a string, keep value from first
- if the values in both elements are dict merge them with priority to first
A possible code is then:
for k, v in first.iteritems():
if isinstance(v, str):
final[k] = v
elif k infinal:
if isinstance(final[k], dict):
final[k].update(first[k])
else:
final[k] =first[k]
else:
final[k] =first[k]
Post a Comment for "Merge Two Dictionaries And Persist The Values Of First Dictionaries"