Is this the correct way of adding the values of two dictionaries? It seems to me that the test for an empty dictionary is superfluous but I'm not sure.
mymodule.py
def merge(dict_1: Union[Dict[str, int], None], dict_2: Union[Dict[str, int], None]) -> dict:
"""
Merge 2 dicts of ints: keys from both dicts, values are the sum of values (one dict can be None).
:dict_1: {"a": 1, "b": 2}
:dict_2: {"a": 3, "c": 3} or None
:return: {"a": 4, "b": 2, "c": 3} or {"a": 1, "b": 2}
"""
if dict_2 is None:
return dict_1
elif dict_1 is None:
return dict_2
result = dict()
for key in dict_1.keys() | dict_2.keys(): # union of all keys
result[key] = dict_1.get(key, 0) + dict_2.get(key, 0) # sum quantities or 0 if key not found
return result
mymodule_test.py
import unittest
import mymodule
class TestMerge(unittest.TestCase):
def test_merge(self) -> None:
dict_1 = {"a": 1, "b": 2}
dict_2 = {"a": 3, "c": 3}
expected = {"a": 4, "b": 2, "c": 3} or {"a": 1, "b": 2}
actual = bestdeck.merge(dict_1, dict_2)
assert expected == actual
def test_empty_merge(self) -> None:
dict_1 = {"a": 1, "b": 2}
dict_2 = None
expected = dict_1
actual = bestdeck.merge(dict_1, dict_2)
assert expected == actual
if __name__ == '__main__':
unittest.main()