Home > Software engineering >  Check if a Dictionary is a Subset of another Dictionary with Key Value pairs
Check if a Dictionary is a Subset of another Dictionary with Key Value pairs

Time:10-20

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?

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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)}

CodePudding user response:

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
  • Related