Added unique utility method.

This commit is contained in:
Fabio Caccamo 2019-10-07 12:03:46 +02:00
parent 2f50c30ea6
commit 1c41219528
3 changed files with 63 additions and 0 deletions

View File

@ -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)

View File

@ -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)

View File

@ -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)