dict.items
in Python 3 returns a view of the dictionary and does not You can concatenate two views. This method would be possible in Python 2, where dict.items
returns a list with key-value pairs in tuples, so you could do res = dict(uno.items() + dos.items())
. This in Python 3 as I say will not work.
You can use dict.update
as sample @ AR4Z in your answer, creating a copy of the dictionary first to prevent the original from being modified if you do not want it to:
import copy
res = copy.copy(uno)
res.update(dos)
In Python> = 3.5 you can use the following syntax instead:
res = {**uno, **dos}
Keep in mind that if there are common keys they will be overwritten depending on the order in which the union is applied. Both methods do not update nested dictionaries:
>>> uno = { "a": {"b": 8, "c": 5}}
>>> dos = {"a": {"b": 68}, "e": 8}
>>> {**uno, **dos}
{'a': {'b': 68}, 'e': 8}
If your dictionaries contain common keys and you want to update at all levels you can use dict.update
but iteratively:
import copy
import collections
def update(dict1, dict2):
for key, value in dict2.items():
if value and isinstance(value, collections.Mapping):
dict1[key] = update(dict1.get(key, {}), value)
else:
dict1[key] = dict2[key]
return dict1
The function updates the last dictionary as the first argument with the second recursively.
An example:
>>> uno = { "a": {"b": 8, "c": 5}}
>>> dos = {"a": {"b": 68}, "e": 8}
>>> res = update(copy.deepcopy(uno), dos)
>>> {'a': {'b': 68, 'c': 5}, 'e': 8}
Created the dictionary you can create the json file with json.dump
, eg:
json.dump(res, "/datos.json")
or a string with json.dumps
.