简体   繁体   中英

Check if a Dictionary is a Subset of another Dictionary with Key Value pairs

I have two Dictionaries resources, and available_resources:

resources = {'B': 1, 's': 2, 't': 3, 'e': 3, '!': 1, 'h': 1, 'i': 1, ' ': 3, 'o': 1, 'g': 1, 'E': 1, 'A': 1, 'x': 2, 'p': 1, 'l': 1, 'r': 1}


available_resources = {'A': 1, 'l': 1, 'g': 1, 'o': 1, 'E': 1, 'x': 1, 'p': 1, 'e': 3, 'r': 1, 't': 3, ' ': 3, 'i': 1, 's': 2, 'h': 1, 'B': 1, '!': 1}

I want to check if resources is a subset of available_resources (if each element contained in the dictionary is <= the corresponding value entry in the resources dictionary)

I've tried:

    if all(available_resources.get(key, None) == val for key, val
                             in resources.items()):
          return True

It is returning false, is there another way I can get it to work?

Could it be a simple sign error? From "==" val to "<=" val? I got true from the below.

if all(available_resources.get(key, None) <= val for key, val
                             in resources.items()):
    return True

If all the values are integers, one approach is to use collections.Counter :

from collections import Counter

resources = {'B': 1, 's': 2, 't': 3, 'e': 3, '!': 1, 'h': 1, 'i': 1, ' ': 3, 'o': 1, 'g': 1, 'E': 1, 'A': 1, 'x': 2, 'p': 1, 'l': 1, 'r': 1}
available_resources = {'A': 1, 'l': 1, 'g': 1, 'o': 1, 'E': 1, 'x': 1, 'p': 1, 'e': 3, 'r': 1, 't': 3, ' ': 3, 'i': 1, 's': 2, 'h': 1, 'B': 1, '!': 1}


res = bool(Counter(resources) - Counter(available_resources))
print(res)

Output

True

You can use the <= operator from sets. This operator determines whether one set is a subset of the other.

As follows:

>>> resources.items() <= available_resources.items()
False

This returns False as there is a difference between the element x in the different dict. You can see this difference using the set operator ^ with will return you the symmetric difference between the dict :

>>> resources.items() ^ available_resources.items()
{('x', 1), ('x', 2)}

You need to use <= instead of ==

>>> all(available_resources.get(k, -1)<=v for k,v in resources.items())
True

Also, above method may fail if resources contains some key that doesn't exist in available_resources , and you can additionally check if the keys in resources are subset of the keys in available_resources for this condition

>>> all(available_resources.get(k, -1)<=v for k,v in resources.items()) and\
        set(resources).issubset(available_resources)
True

I have tested the answers in this stackoverflow question: click here

And i think it's works for you!

all(item in available_resources.items() for item in resources.items())

# - or - # 

available_resources.items() <= resources.items()

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