Check if a specific Key and a value exist in a dictionary
Question: I am trying to determine if a specific key and value pair exist in a
dictionary; however, if I use the contains or has-key method, it only checks
for the key. I need it to check both the key and the specific value. Some
background: We have a total of 4 dictionaries: one for A, B, CompareList, and
ChangeList. Once A is initialized, I put A's contents into CompareList (I
would compare them directly; but A and B are double hash tables. And I've
tried all of the methods here; but none of them work for me). So once we put A
into CompareList, I compare it with the ObjectAttributes dictionary in B to
see if anything changed. So for example, B may have the key,value pairs
shape:circle and fill:no. If CompareList had shape:circle and fill:yes, then I
want only fill:yes to be ChangeList. The problem lies in the "if
attributes.getName() not in self.CompareList:" line. Here is the code; I am
running it on Python 2.7.8. Thanks in advance for any help!!

    
    
    class ObjectSemanticNetwork:
        def __init__(self):
            self.ObjectNames = {}
            self.ObjectAttributes = {}
    
        def setName(self, name):
            self.ObjectNames[name] = self.ObjectAttributes
    
        def setData(self, name, attribute):
            self.ObjectAttributes[name] = attribute
    
        def checkData(self, key):
            print(key)
            for key, value in self.ObjectAttributes.iteritems():
                print(key)
                print(value)
                print("\n")
    class Agent:
    (self):
            self.CompareList = {}
            self.ChangeListAB = {}
            self.ChangeListCD = {}
    
        def addToCompareList(self, name, value):
            self.CompareList[name] = value
    
        def addToChangeListAB(self, name, value):
            self.ChangeListAB[name] = value
    
        def addToChangeListCD(self, name, value):
            self.ChangeListCD[name] = value
    
        def CheckList(self, List, ListName):
            print '-------------------------',ListName,'--------------------------------'
            for key, value in List.iteritems():
                print(key)
                print(value)
    
        def Solve(self,problem):
            OSNAB = ObjectSemanticNetwork()
            for object in problem.getFigures().get("A").getObjects():
                for attributes in object.getAttributes():
                    self.addToCompareList(attributes.getName(), attributes.getValue())
                    OSNAB.ObjectNames["A"] = OSNAB.setData(attributes.getName(), attributes.getValue())
            #OSNAB.checkData("A")
            self.CheckList(self.CompareList,"CompareList")
    
            for object in problem.getFigures().get("B").getObjects():
                for attributes in object.getAttributes():
                    if attributes.getName() not in self.CompareList:
                        self.addToChangeListAB(attributes.getName(), attributes.getValue())
                    OSNAB.ObjectNames["B"] = OSNAB.setData(attributes.getName(), attributes.getValue())
            # OSNAB.checkData("B")
            self.CheckList(self.ChangeListAB,"ChangeList")
    
            OSNCD = ObjectSemanticNetwork()
            for object in problem.getFigures().get("C").getObjects():
                for attributes in object.getAttributes():
                    OSNCD.ObjectNames["C"] = OSNCD.setData(attributes.getName(), attributes.getValue())
            # OSNCD.checkData("C")
    
            for object in problem.getFigures().get("1").getObjects():
                for attributes in object.getAttributes():
                    OSNCD.ObjectNames["D"] = OSNCD.setData(attributes.getName(), attributes.getValue())
            # OSNCD.checkData("D")
    
            return "6"
    


Answer: Use

    
    
    if key in d and d[key] == value:
    

Or (only in Python 3)

    
    
    if (key, value) in d.items():
    

In Python 3 `d.items()` returns a [Dictionary view
object](https://docs.python.org/3.4/library/stdtypes.html#dictionary-view-
objects), which supports fast membership testing. In Python 2 `d.items()`
returns a list, which is both slow to create and slow to to test membership.
Python 2.7 is a special case where you can use `d.viewitems()` and get the
same thing that you get with `d.items()` in Python 3.

**Edit:** In a comment you indicate that for performance reasons you prefer
`checkKeyValuePairExistence` over `key in d and d[key] == value`. Below are
some timings showing that `checkKeyValuePairExistence` is always slower (by
about 2x on my system when the key-value pair is present 16x when it is not).
I also tested larger and smaller dictionaries and found little variation in
the timings.

    
    
    >>> import random
    >>> from timeit import timeit
    >>> def checkKeyValuePairExistence(dic, key, value):
    ...     try:
    ...         return dic[key] == value
    ...     except KeyError:
    ...         return False
    ...
    >>> d = {random.randint(0, 100000):random.randint(0, 100000) for i in range(1000)}
    >>> setup = 'from __main__ import k, d, v, checkKeyValuePairExistence'
    >>> test_try_except = 'checkKeyValuePairExistence(d, k, v)'
    >>> test_k_in_d_and = 'k in d and d[k] == v'
    >>> k, v = random.choice(d.items()) # to test if found
    >>> timeit(test_try_except, setup=setup)
    0.1984054392365806
    >>> timeit(test_k_in_d_and, setup=setup)
    0.10442071140778353
    >>> k = -1 # test if not found
    >>> timeit(test_try_except, setup=setup)
    1.2896073903002616
    >>> timeit(test_k_in_d_and, setup=setup)
    0.07827843747497809 
    

