Created
April 14, 2020 15:52
-
-
Save adamabernathy/b2488b82e4cbef36532b0eaf22bc3627 to your computer and use it in GitHub Desktop.
Safely merge two Python dictionaries
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
def merge_dict(dict1, dict2): | |
res = {**dict1, **dict2} | |
return res |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
import pytest | |
from lib.merge_dict import merge_dict | |
def test(): | |
dict1 = {"a": 1, "b": 2} | |
dict2 = {"d": 4, "c": 3} # note the swap | |
result = merge_dict(dict1, dict2) | |
# {"b": 2, "a": 1, "c": 3, "d": 4} | |
assert sorted(result.keys()) == ["a", "b", "c", "d", ] | |
assert result["a"] == 1 | |
assert result["b"] == 2 | |
assert result["c"] == 3 | |
assert result["d"] == 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment