如何在Python中检查字典中是否至少有一个键作为值存在于另一个字典中?

如何在Python中检查字典中是否至少有一个键作为值存在于另一个字典中?,python,Python,我正在创建一个函数,该函数接受dictionary1并检查是否有任何键作为值dictionary2存在 我尝试过使用dictionary2.isdisjoint(dictionary1),但这只对检查键有效 如何在Python中检查键到值?如果下面的语句返回True(它将返回公共值),则: 说明: set([3]) dictionary1.keys()将给出dictionary1中的键列表 dictionary2.values()将给出dictionary2中的值列表 将这两个值转换为set

我正在创建一个函数,该函数接受dictionary1并检查是否有任何键作为值dictionary2存在

我尝试过使用
dictionary2.isdisjoint(dictionary1)
,但这只对检查键有效


如何在Python中检查键到值?

如果下面的语句返回
True
(它将返回公共值),则:

说明:

set([3])
  • dictionary1.keys()
    将给出dictionary1中的键列表

  • dictionary2.values()
    将给出dictionary2中的值列表

  • 将这两个值转换为
    set
    ,如果它们有公共值,则结束 找出两者之间的共同值
输出:

set([3])

这不是一个内置的操作。您需要编写逻辑来自己完成。您似乎正在使用Python3,因此下面类似的内容可能会起作用

>x=dict.fromkeys([0,5,10])
>>>y={x:x表示范围(5)内的x}
>>>打印(x.keys().isdisjoint(y.values()))
假的
>>>x.pop(0)
>>>打印(x.keys().isdisjoint(y.values()))
真的

不确定这是否真的是一个足够大的任务,可以放入一个单独的函数中,但无论如何,下面是一个使用关键字的示例:


你的解决方案几乎是正确的。您必须添加
not
来证明相反的结果(not disjoint==具有公共元素),并使用方法
values()
从字典中获取值。在您的情况下,只检查两个字典的键

d1 = {i: i for i in range(5)}
d2 = {i: j for i, j in zip(range(5), range(5,10))}
d3 = {i: j for i, j in zip(range(5,10), range(5))}

print('d1: ', d1)
print('d2: ', d2)

print('Keys of d1 in values of d2: ', not set(d1).isdisjoint(d2.values()))
print('Keys of d1 in keys of d2: ', not set(d1).isdisjoint(d2))
print()

print('d2: ', d2)
print('d3: ', d3)

print('Keys of d2 in values of d3: ', not set(d2).isdisjoint(d3.values()))
print('Keys of d2 in keys of d3: ', not set(d2).isdisjoint(d3))
输出:
他们尝试了“dictionary2.isdisjoint(dictionary1)”。也许他们可以提供一幅漫画,请点击旁边的勾号,接受帮助您解决问题的答案,谢谢!优雅的python风格。
set(dictionary1)和set(dictionary2.values())
甚至更好
d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'}
d2 =  {'5': 'five', '6': 'six', '7': 'eight', 'three': '3', '9': 'nine'}

for key in d:
    if key in d2.itervalues():
        print "found"
if any(k in d2.values() for k in d1.keys()):
    # do stuff
d1 = {i: i for i in range(5)}
d2 = {i: j for i, j in zip(range(5), range(5,10))}
d3 = {i: j for i, j in zip(range(5,10), range(5))}

print('d1: ', d1)
print('d2: ', d2)

print('Keys of d1 in values of d2: ', not set(d1).isdisjoint(d2.values()))
print('Keys of d1 in keys of d2: ', not set(d1).isdisjoint(d2))
print()

print('d2: ', d2)
print('d3: ', d3)

print('Keys of d2 in values of d3: ', not set(d2).isdisjoint(d3.values()))
print('Keys of d2 in keys of d3: ', not set(d2).isdisjoint(d3))
# d1:  {0: 0, 1: 1, 2: 2, 3: 3, 4: 4}
# d2:  {0: 5, 1: 6, 2: 7, 3: 8, 4: 9}
# Keys of d1 in values of d2:  False
# Keys of d1 in keys of d2:  True
# 
# d2:  {0: 5, 1: 6, 2: 7, 3: 8, 4: 9}
# d3:  {5: 0, 6: 1, 7: 2, 8: 3, 9: 4}
# Keys of d2 in values of d3:  True
# Keys of d2 in keys of d3:  False