Skip to content

Instantly share code, notes, and snippets.

@Mikael-Lovqvist
Created June 1, 2022 08:59
Show Gist options
  • Save Mikael-Lovqvist/d383deec522c6c8170d460bd879cb887 to your computer and use it in GitHub Desktop.
Save Mikael-Lovqvist/d383deec522c6c8170d460bd879cb887 to your computer and use it in GitHub Desktop.
A simple class for filtering mappings
class dict_filter:
def __init__(self, key=None, value=None, key_condition=None, value_condition=None):
self.key = key
self.value = value
self.key_condition = key_condition
self.value_condition = value_condition
def __call__(self, source):
K, V, KC, VC = self.key, self.value, self.key_condition, self.value_condition
if KC and VC:
if K and V:
return {K(k): V(v) for k, v in source.items() if KC(k) and VC(v)}
elif K:
return {K(k): v for k, v in source.items() if KC(k) and VC(v)}
elif V:
return {k: V(v) for k, v in source.items() if KC(k) and VC(v)}
else:
return {k: v for k, v in source.items() if KC(k) and VC(v)}
elif KC:
if K and V:
return {K(k): V(v) for k, v in source.items() if KC(k)}
elif K:
return {K(k): v for k, v in source.items() if KC(k)}
elif V:
return {k: V(v) for k, v in source.items() if KC(k)}
else:
return {k: v for k, v in source.items() if KC(k)}
elif VC:
if K and V:
return {K(k): V(v) for k, v in source.items() if VC(v)}
elif K:
return {K(k): v for k, v in source.items() if VC(v)}
elif V:
return {k: V(v) for k, v in source.items() if VC(v)}
else:
return {k: v for k, v in source.items() if VC(v)}
else:
if K and V:
return {K(k): V(v) for k, v in source.items()}
elif K:
return {K(k): v for k, v in source.items()}
elif V:
return {k: V(v) for k, v in source.items()}
else:
return dict(source)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment