Check if a dictionary is a subset of another dictionary

I am trying to compare 2 strings and check if all characters in String are present a

in String b

. I am currently using the following method, converting a string to a dictionary and comparing it to another. But there are many chances that it gives a false result.

x = 'NJITZU THE HANDS OF TIME'
y = 'NinjaGo Masters of Spinjitzu The Hands of Time'
if Counter(x) < Counter(y):
    print 'Yes'
else:
    print 'No'

      

Please suggest a better way to do this

+3


source to share


3 answers


If I understand your problem correctly, you don't need to compare dictionaries, but sets:

>>> x = 'NJITZU THE HANDS OF TIME'
>>> y = 'NinjaGo Masters of Spinjitzu The Hands of Time'
>>> set(x).issubset(set(y))
False

      

And if you want case insensitivity, you can call lower()

for both lines:



>>> set(x.lower()).issubset(set(y.lower()))
True

      

You can also compare whole words using split()

:

>>> set(x.lower().split())
set(['of', 'the', 'time', 'njitzu', 'hands'])
>>> set(x.lower().split()).issubset(set(y.lower().split()))
False
>>> set('SPINJITZU THE HANDS OF TIME'.lower().split()).issubset(set(y.lower().split()))
True

      

+5


source


I would use an object set

. The documentation can be found here.

x = 'NJITZU THE HANDS OF TIME'
y = 'NinjaGo Masters of Spinjitzu The Hands of Time'
if set(x.lower()) <= set(y.lower()):
    print('Yes')
else:
    print('No')

      



The operator is <

overloaded before is_subset

. I also converted the strings to lowercase to get the answer to printing "Yes".

+2


source


You can use the built-in all for this .

all(character in y for character in x)

      

all () will return true if each element is true and false otherwise. We use in

to check if a character is in the string y

and we will do that for each one character in x

.

+1


source







All Articles