Added filter utility method.

This commit is contained in:
Fabio Caccamo 2019-07-02 15:15:31 +02:00
parent e8a2d32612
commit 3e934e245b
5 changed files with 48 additions and 0 deletions

View File

@ -64,6 +64,13 @@ s = d.dump_items(key=None)
print(s)
```
```python
# Return a filtered dict using the given predicate function.
# Predicate function receives key, value arguments and should return a bool value.
predicate = lambda k, v: v is not None
d.filter(predicate)
```
```python
# Get value by key or keypath trying to return it as bool.
# Values like `1`, `true`, `yes`, `on`, `ok` will be returned as `True`.

View File

@ -75,6 +75,13 @@ API
s = d.dump_items(key=None)
print(s)
.. code:: python
# Return a filtered dict using the given predicate function.
# Predicate function receives key, value arguments and should return a bool value.
predicate = lambda k, v: v is not None
d.filter(predicate)
.. code:: python
# Get value by key or keypath trying to return it as bool.

View File

@ -26,6 +26,10 @@ class benedict(KeypathDict, ParseDict, UtilityDict):
def deepcopy(self):
return super(benedict, self).deepcopy()
@benediction
def filter(self, func):
return super(benedict, self).filter(func)
@classmethod
@benediction
def fromkeys(cls, sequence, value=None):

View File

@ -43,3 +43,14 @@ class UtilityDict(dict):
def dump_items(self, key=None):
return self.dump(self.get(key) if key else self)
def filter(self, predicate):
if not callable(predicate):
raise ValueError('predicate argument must be a callable.')
d = {}
keys = self.keys()
for key in keys:
val = self.get(key, None)
if predicate(key, val):
d[key] = val
return d

View File

@ -154,3 +154,22 @@ class UtilityDictTestCase(unittest.TestCase):
output = b.dump_items()
self.assertEqual(output, expected_output)
def test_filter(self):
d = {
'a': 1,
'b': 2,
'c': '4',
'e': '5',
'f': 6,
'g': 7,
}
b = UtilityDict(d)
f = b.filter(lambda key, val: isinstance(val, int))
r = {
'a': 1,
'b': 2,
'f': 6,
'g': 7,
}
self.assertEqual(f, r)