diff --git a/benedict/core/swap.py b/benedict/core/swap.py index 6c5806f6..4358c199 100644 --- a/benedict/core/swap.py +++ b/benedict/core/swap.py @@ -4,4 +4,8 @@ def swap(d, key1, key2): if key1 == key2: return - d[key1], d[key2] = d[key2], d[key1] + val1 = d[key1] + val1 = val1.copy() if isinstance(val1, dict) else val1 + val2 = d[key2] + val2 = val2.copy() if isinstance(val2, dict) else val2 + d[key1], d[key2] = val2, val1 diff --git a/tests/dicts/test_benedict.py b/tests/dicts/test_benedict.py index 97353d68..4aeabf38 100644 --- a/tests/dicts/test_benedict.py +++ b/tests/dicts/test_benedict.py @@ -2081,6 +2081,22 @@ def test_swap_with_keypath(self): b = benedict(d) b.swap("a.y", "b.y") b.swap("b.x", "c.x") + r = { + "a": { + "x": 1, + "y": 2, + }, + "b": { + "x": 3, + "y": 1, + }, + "c": { + "x": 2, + "y": 3, + }, + } + self.assertEqual(b, r) + b.swap("a", "c") r = { "a": {