Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a dictionary is in another dictionary in python

I have an objects

>>> L[0].f.items()
dict_items([('a', 1)])
>>> a3.f.items()
dict_items([('a', 1), ('c', 3)])

I want to test if L[0].f.items() is a subset of a3.f.items(). So I did the following:

>>> L[0].f.items() in a3.f.items()
False

But I expect that L[0].f.items() is a subset of a3.f.items(). Why it returns False? How can I test if a dictionary items is a subset of another dictionary items?

like image 701
user2192774 Avatar asked Dec 21 '22 01:12

user2192774


2 Answers

You can make sets from the lists and see if one set is a subset of another:

>>> list1 = [('a', 1), ('c', 3)]
>>> list2 = [('a', 1)]
>>> set(list2).issubset(list1)
True

Or, in your case:

set(L[0].f.items()).issubset(set(a3.f.items()))
like image 166
alecxe Avatar answered May 25 '23 00:05

alecxe


in tests whether the left operand is an element of the right. Since dict item views are set-like, you want <=, which tests whether one is a subset of another:

>>> L[0].f.items() <= a3.f.items()
True

If you want to do this with lists or other non-set-like iterables, you can build a set out of one and use issuperset:

>>> more = [1, 2, 3]
>>> less = [1, 2]
>>> set(more).issuperset(less)
True
like image 29
user2357112 supports Monica Avatar answered May 25 '23 02:05

user2357112 supports Monica