检查特定键和值是否存在于字典中

2024-10-17 06:31:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图确定字典中是否存在特定的键和值对;但是,如果使用contains或has key方法,它只检查键。我需要它检查键和具体值。一些背景: 我们总共有4本字典:一本是a、B、CompareList和ChangeList。初始化A之后,我将A的内容放入CompareList(我将直接比较它们;但是A和B是双哈希表。我已经尝试过这里所有的方法,但是没有一种对我有效)。因此,一旦我们将A放入CompareList,我将它与B中的ObjectAttributes字典进行比较,看看是否有任何变化。例如,B可以有键,值对shape:circle和fill:no。如果CompareList有shape:circle和fill:yes,那么我只希望fill:yes是变更列表。问题在于“if attributes.getName()不在self.CompareList:”行中。这是代码;我在Python2.7.8上运行它。提前感谢您的帮助!!

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"

Tags: keynameinselfforobjectvaluedef
3条回答

这个功能怎么样:

def checkKeyValuePairExistence(dic, key, value):
    try:
        return dic[key] == value
    except KeyError:
        return False

如果您使用的是python提供的另一种类型的字典(很抱歉,我无法从您的文章中理解您是否使用它),那么请告诉我,我将尝试为您提供另一种解决方案

为什么不这样做:

a = {1:'a', 2:'b'}
b = (1, 'a')
print b in a.iteritems() # prints True

使用

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

或(仅在Python3中)

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

在Python 3中,d.items()返回一个Dictionary view object,它支持快速的成员资格测试。在Python 2中,d.items()返回一个列表,该列表创建速度慢,测试成员身份也慢。Python 2.7是一个特殊情况,在这里您可以使用d.viewitems(),并获得与Python 3中的d.items()相同的结果。

编辑:在注释中,您表示出于性能原因,您更喜欢checkKeyValuePairExistence而不是key in d and d[key] == value。下面是一些计时,显示checkKeyValuePairExistence总是慢一些(在我的系统上,当键值对存在时大约慢2倍,当键值对不存在时则慢16倍)。我还测试了越来越大的字典,发现时间变化不大。

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

相关问题 更多 >