diff --git a/benedict/dicts/__init__.py b/benedict/dicts/__init__.py index bd4dc98..3dfac0d 100644 --- a/benedict/dicts/__init__.py +++ b/benedict/dicts/__init__.py @@ -114,3 +114,6 @@ class benedict(IODict, KeypathDict, ParseDict): for key in keys: d[key] = self.get(key, None) return d + + def swap(self, key1, key2): + self[key1], self[key2] = self[key2], self[key1] diff --git a/tests/test_benedict.py b/tests/test_benedict.py index c594424..0c43f20 100644 --- a/tests/test_benedict.py +++ b/tests/test_benedict.py @@ -1093,3 +1093,63 @@ class BenedictTestCase(unittest.TestCase): self.assertTrue(isinstance(f, benedict)) self.assertEqual(f.get('x.a'), 1) self.assertEqual(f.get('y.b'), 2) + + def test_swap(self): + d = { + 'a': 1, + 'b': 2, + 'c': 3, + } + b = benedict(d) + b.swap('a', 'b') + r = { + 'a': 2, + 'b': 1, + 'c': 3, + } + self.assertEqual(b, r) + + def test_swap_with_invalid_key(self): + d = { + 'a': 1, + 'b': 2, + 'c': 3, + } + b = benedict(d) + with self.assertRaises(KeyError): + b.swap('a', 'd') + + def test_swap_with_keypath(self): + d = { + 'a': { + 'x': 1, + 'y': 1, + }, + 'b': { + 'x': 2, + 'y': 2, + }, + 'c': { + 'x': 3, + 'y': 3, + }, + } + b = benedict(d) + b.swap('a.y', 'b.y') + b.swap('b.x', 'c.x') + b.swap('a', 'c') + r = { + 'a': { + 'x': 2, + 'y': 3, + }, + 'b': { + 'x': 3, + 'y': 1, + }, + 'c': { + 'x': 1, + 'y': 2, + }, + } + self.assertEqual(b, r)