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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25711660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:32:40  来源:igfitidea点击:

Check if a specific Key and a value exist in a dictionary

pythondictionary

提问by Elijah Philpotts

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

我正在尝试确定字典中是否存在特定的键和值对;但是,如果我使用 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 是ChangeList。问题在于“if 属性。

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"

采纳答案by tomer.z

How about this function:

这个功能怎么样:

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

If you are using another type of dictionary other then the one python offers (I'm sorry, I couldnt understand from your post if you are using it or not) then let me know and i'll try to give your another solution

如果您使用的是 Python 提供的另一种类型的字典(对不起,我无法从您的帖子中理解您是否正在使用它)然后告诉我,我会尝试为您提供另一种解决方案

回答by Steven Rumbalski

Use

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

Or (only in Python 3)

或者(仅在 Python 3 中)

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

In Python 3 d.items()returns a Dictionary view object, 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.

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

Edit:In a comment you indicate that for performance reasons you prefer checkKeyValuePairExistenceover key in d and d[key] == value. Below are some timings showing that checkKeyValuePairExistenceis 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.

编辑:在评论你表明,对于性能方面的原因,你喜欢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 

回答by Chrispresso

Why not just do this:

为什么不这样做:

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