简体   繁体   中英

Check if a dictionary is subset of another dictionary

I am trying to compare 2 Strings and check if all characters in String a are present in String b . I am currently using the following method by converting the string into a dictionary and comparing it with the other. But there are many chances that it gives a false positive.

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 any better way to do this

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 a case-insensitive compare, you can call lower() on both strings:

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

You could also compare whole words by 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

I would use the set object. 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 to be is_subset . To get the answer to print "Yes", I've also converted the strings to lowercase.

You can use the builtin all function for this.

all(character in y for character in x)

all() will return true if every element is true and false otherwise. We use in to check if a character is in the string y and we will do this for every character in x .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM