From 1c4121952828c54bf322a2d67897a56d8920cfe0 Mon Sep 17 00:00:00 2001 From: Fabio Caccamo Date: Mon, 7 Oct 2019 12:03:46 +0200 Subject: [PATCH] Added unique utility method. --- benedict/dicts/__init__.py | 3 +++ benedict/utils/dict_util.py | 11 +++++++++ tests/test_benedict.py | 49 +++++++++++++++++++++++++++++++++++++ 3 files changed, 63 insertions(+) diff --git a/benedict/dicts/__init__.py b/benedict/dicts/__init__.py index 22340fc..313700f 100644 --- a/benedict/dicts/__init__.py +++ b/benedict/dicts/__init__.py @@ -98,3 +98,6 @@ class benedict(IODict, KeypathDict, ParseDict): def swap(self, key1, key2): dict_util.swap(self, key1, key2) + + def unique(self): + dict_util.unique(self) diff --git a/benedict/utils/dict_util.py b/benedict/utils/dict_util.py index 9264cbb..57d2185 100644 --- a/benedict/utils/dict_util.py +++ b/benedict/utils/dict_util.py @@ -110,3 +110,14 @@ def subset(d, keys, *args): def swap(d, key1, key2): d[key1], d[key2] = d[key2], d[key1] + + +def unique(d): + values = [] + keys = sorted(d.keys()) + for key in keys: + value = d.get(key, None) + if value in values: + d.pop(key, None) + continue + values.append(value) diff --git a/tests/test_benedict.py b/tests/test_benedict.py index 19afff9..dba3f99 100644 --- a/tests/test_benedict.py +++ b/tests/test_benedict.py @@ -1194,3 +1194,52 @@ class BenedictTestCase(unittest.TestCase): }, } self.assertEqual(b, r) + + def test_unique(self): + d = { + 'a': { + 'x': 1, + 'y': 1, + }, + 'b': { + 'x': 2, + 'y': 2, + }, + 'c': { + 'x': 1, + 'y': 1, + }, + 'd': { + 'x': 1, + }, + 'e': { + 'x': 1, + 'y': 1, + 'z': 1, + }, + 'f': { + 'x': 2, + 'y': 2, + }, + } + b = benedict(d) + b.unique() + r = { + 'a': { + 'x': 1, + 'y': 1, + }, + 'b': { + 'x': 2, + 'y': 2, + }, + 'd': { + 'x': 1, + }, + 'e': { + 'x': 1, + 'y': 1, + 'z': 1, + }, + } + self.assertEqual(b, r)