0

A way to find if an object is a sub-object of another?

Is there an operator or built-in function in python where I can do something like the following?

>>> needle={"age": 10, "name": "peter"}
>>> haystack={"age":10, "name": "peter", "height": 100}
>>> needle & haystack == haystack

The equivalent, I suppose, of set-intersection, but now with key-value pairs.

Is there a name for this in intersection-on-maps in programming?

One roundabout way of doing this is the following:

>>> set(needle.items()) & set(haystack.items()) == set(needle.items())
True
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
David542
  • 104,438
  • 178
  • 489
  • 842

2 Answers2

2

Dictionary view objects behave similar to set in Python 3 (excluding dict_values), and you can use comparison operators to test whether a set is a [proper] subset of another set:

>>> needle = {'age': 10, 'name': 'peter'}
>>> haystack = {'age': 10, 'name': 'peter', 'height': 100}
>>> needle.items() <= haystack.items()
True
Mechanic Pig
  • 6,756
  • 3
  • 10
  • 31
1

I think we can do this as well (python version should be 3.8+):

needle={"age": 10, "name": "peter"}
haystack={"age":10, "name": "peter", "height": 100}

def check_subset(haystack,needle):
  return haystack | needle == haystack

Here in the above code haystack is the big dictionary and needle is the small dictionary.

Since we join both the dictionaries if the output is equal to the larger dictionary then it means that the smaller dictionary is the subset of larger dictionary.


One more way is to just unpack them and compare them with larger dictionary:

{**haystack, **needle} == haystack
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44