Skip to content

Instantly share code, notes, and snippets.

@adamabernathy
Created April 14, 2020 15:52
Show Gist options
  • Save adamabernathy/b2488b82e4cbef36532b0eaf22bc3627 to your computer and use it in GitHub Desktop.
Save adamabernathy/b2488b82e4cbef36532b0eaf22bc3627 to your computer and use it in GitHub Desktop.
Safely merge two Python dictionaries
# coding: utf-8
def merge_dict(dict1, dict2):
res = {**dict1, **dict2}
return res
# 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