Created
February 7, 2022 08:42
-
-
Save mhugo/f7a135b4f4eeb39082598c75c0e186a0 to your computer and use it in GitHub Desktop.
Ordered dict with predicate filtering
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import OrderedDict | |
from enum import Enum | |
from typing import Any, Callable, Dict, Optional | |
class SubOrderedDict(dict): | |
def __init__(self, original_dict: OrderedDict, predicate: Optional[Callable[[Any], bool]] = None): | |
self._dict = original_dict | |
self._predicate = predicate or (lambda _: True) | |
def __iter__(self): | |
# iterator over keys | |
for key, value in self._dict.items(): | |
if self._predicate(value): | |
yield key | |
def items(self): | |
for key, value in self._dict.items(): | |
if self._predicate(value): | |
yield key, value | |
def __and__(self, other): | |
# insersection | |
return SubOrderedDict( | |
self._dict, | |
lambda value: self._predicate(value) and other._predicate(value)) | |
def __or__(self, other): | |
# union | |
return SubOrderedDict( | |
self._dict, | |
lambda value: self._predicate(value) or other._predicate(value)) | |
def __sub__(self, other): | |
# difference | |
return SubOrderedDict( | |
self._dict, | |
lambda value: self._predicate(value) and not other._predicate(value)) | |
class FieldType(Enum): | |
TECHNICAL = 0 | |
VIRTUAL = 1 | |
REGULAR = 2 | |
d = OrderedDict() | |
d["a"] = ("A", FieldType.TECHNICAL) | |
d["b"] = ("B", FieldType.TECHNICAL) | |
d["b2"] = ("B2", FieldType.REGULAR) | |
d["c"] = ("C", FieldType.VIRTUAL) | |
d["d"] = ("D", FieldType.TECHNICAL) | |
technicals = SubOrderedDict(d, lambda v: v[1] == FieldType.TECHNICAL) | |
virtuals = SubOrderedDict(d, lambda v: v[1] == FieldType.VIRTUAL) | |
all = SubOrderedDict(d) | |
sub1 = technicals | virtuals | |
regulars = all - technicals - virtuals | |
for n, o in [("technicals", technicals), ("virtuals", virtuals), ("sub1", sub1), ("regulars", regulars)]: | |
print("=={}==".format(n)) | |
for k, v in o.items(): | |
print(k, v) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment