Skip to content

Instantly share code, notes, and snippets.

@theY4Kman
Created October 28, 2016 14:38
Show Gist options
  • Save theY4Kman/5b0cd4b77a0e8862206437b7c000c0b5 to your computer and use it in GitHub Desktop.
Save theY4Kman/5b0cd4b77a0e8862206437b7c000c0b5 to your computer and use it in GitHub Desktop.
Some sugar to ease dict subset checking.
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