Created
October 28, 2016 14:38
-
-
Save theY4Kman/5b0cd4b77a0e8862206437b7c000c0b5 to your computer and use it in GitHub Desktop.
Some sugar to ease dict subset checking.
This file contains hidden or 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
def dict_contains_subset(superset, subset): | |
for key, value in subset.iteritems(): | |
if key not in superset or superset[key] != value: | |
return False | |
else: | |
return True | |
class SupersetDict(dict): | |
def __contains__(self, other): | |
if isinstance(other, dict): | |
return dict_contains_subset(self, other) | |
else: | |
return super(SupersetDict, self).__contains__(other) | |
superset = SupersetDict | |
if __name__ == '__main__': | |
print {'a': 1} in {'a': 1} | |
# TypeError: unhashable type: 'dict' | |
print {'a': 1} in superset({'a': 1}) | |
# True | |
print {'a': 1} in superset({'a': 1, 'b': 2}) | |
# True | |
print {'a': 1} in superset({'b': 2}) | |
# False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment