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

I have objects

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

I want to check 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 L [0] .f.items () to be a subset of a3.f.items (). Why does it return False? How to check if dictionary elements are a subset of other dictionary elements?

+4
source share
4 answers

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

 >>> 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())) 
+6
source

You check to see if the actual list is there, not a tuple. Here you can use all() :

 all(i in a3.f.items() for i in L[0].f.items()) 

Or even set the notation:

 >>> set(L[0].f.items()) & set(a3.f.items())) == set(L[0].f.items()) True # Note that without the bool call this returns set([('a', 1)]), which can # be useful if you have more than one sublist tuples. 
+2
source

in checks if the left operand is an element on the right. Since the item element item representations are specified, you want a <= , which checks if this is a subset of the other:

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

If you want to do this with lists or other non-standard iterators, you can build a set from one and use issuperset :

 >>> more = [1, 2, 3] >>> less = [1, 2] >>> set(more).issuperset(less) True 
+2
source

With Python 2.7, you have dict.viewitems() which will provide you with behavior similar to a set. (Oh, you seem to be using Py3, since you have dict_items() objects!)

So you can use

 a = dict(a=1) b = dict(a=1, c=3) ai = a.viewitems() # items() on 3.x bi = b.viewitems() # items() on 3.x ai - bi # gives a set([]) bi - ai # gives a set([('c', 3)]) ai & bi # gives ai ai | bi # gives bi 

As you want to make sure that each element of a also contained in b , you need

 ai & bi == ai 

If this is not the case, a does not contain the element a , <disturbing " & .

EDIT: But it's even easier - just

 ai <= bi 

as you could do on the set.

+1
source

Source: https://habr.com/ru/post/1496389/


All Articles