在包含python中特定值的字典中查找键值对

在包含python中特定值的字典中查找键值对,python,pandas,dictionary,Python,Pandas,Dictionary,在Python3和Python2中,是否有方法在包含特定值的字典中获取键值对?这是字典: dict_a = {'key_1': [23, 'ab', 'cd'], 'key_2': [12, 'aa', 'hg']} 如何获取值中存在“cd”的键值对?我尝试使用itervalues(),但似乎不起作用您可以使用简单的字典理解来检查cd是否在每个键、值对的值中: >>> dict_a = {'key_1': [23, 'ab', 'cd'], 'key_2': [12, 'aa

在Python3和Python2中,是否有方法在包含特定值的字典中获取键值对?这是字典:

dict_a = {'key_1': [23, 'ab', 'cd'], 'key_2': [12, 'aa', 'hg']}

如何获取值中存在“cd”的键值对?我尝试使用itervalues(),但似乎不起作用

您可以使用简单的字典理解来检查
cd
是否在每个键、值对的值中:

>>> dict_a = {'key_1': [23, 'ab', 'cd'], 'key_2': [12, 'aa', 'hg']}
>>> {k: v for k, v in dict_a.items() if 'cd' in v}
{'key_1': [23, 'ab', 'cd']}
这可以通过将逻辑提取到函数中来概括:

>>> def filter_dict(d, key):
    return {k: v for k, v in d.items() if key in v}

>>> dict_a = {'key_1': [23, 'ab', 'cd'], 'key_2': [12, 'aa', 'hg']}
>>> filter_dict(dict_a, 'cd')
{'key_1': [23, 'ab', 'cd']}
>>>

dict

dict_a = {'key_1': [23, 'ab', 'cd'], 'key_2': [12, 'aa', 'hg']}
for k, v in dict_a.iteritems():
    if 'cd' in v:
        print k, v

key_1 [23, 'ab', 'cd']

您只需在字典项中循环,检查您的值是否在值中,例如:

for k, v in dict_a.items():  # use iteritems() on Python 2.x
    if "cd" in v:
        print("key: {}, value: {}".format(k, v))

您可以编写自己的小方法来检查字典中的值

dict_a = {'key_1': [23, 'ab', 'cd'], 'key_2': [12, 'aa', 'hg']}

def checkValue(dictionary, value):
    for key, valueList in dict_a.items():
        if value in valueList:
            print("value(" + value + ") present in " + str(valueList) + " with key (" + key + ")")
            break

checkValue(dict_a, 'cd')
样本运行

value(cd) present in [23, 'ab', 'cd'] with key (key_1)

谢谢@Christian,我得到了这个错误:
***AttributeError:'dict'对象没有属性'iteritems'
@user308827啊,比您使用的Python 3还多。您需要改用
.items()
。我会更新的。再查一遍。现在应该可以了。你把我甩了,因为你在问题中提到了
itervalues()
,所以我以为你在使用python2。