python - 检查字典中是否存在特定的键和值

标签 python dictionary

我正在尝试确定字典中是否存在特定的键和值对;但是,如果我使用 contains 或 has-key 方法,它只会检查 key 。我需要它来检查 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 是ChangeList。问题在于“if attributes.getName() not in self.CompareList:”行。这是代码;我在 Python 2.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"

最佳答案


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

或者(仅在 Python 3 中)
if (key, value) in d.items():

在 Python 3 中 d.items()返回 Dictionary view object ,支持快速成员(member)测试。在 Python 2 中 d.items()返回一个列表,该列表创建和测试成员资格都很慢。 Python 2.7 是一种特殊情况,您可以使用 d.viewitems()并获得与 d.items() 相同的东西在 Python 3 中。

编辑:在评论中,您表明出于性能原因您更喜欢 checkKeyValuePairExistencekey 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 

关于python - 检查字典中是否存在特定的键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25711660/

相关文章:

python - 从 PySpark DataFrame 中的 Python 列表列表中删除一个元素

dictionary - Python中由列表组成的字典值的列元素之和

powershell - 哈希表和字典的正式区别是什么?

python - ModelViewSet API 端点是什么

python - 如何从 C 访问 Python 全局变量?

python - 计算 python 中第二个列表中列表项的出现次数

python - 类型错误 : __init__() got multiple values for keyword argument 'encoding'

python - 如何实现通过嵌套字典查找关键路径的函数 max_leaf_path(d) ?

java - 使用 SnakeYAML 编写 YAML 文件

python - 通过迭代重命名Python嵌套字典中的键和子键