簡體   English   中英

如何檢查字典中的至少一個鍵是否在Python中的另一個字典中作為值存在?

[英]How to check if at least one key in dictionary exists as a value in another dictionary in Python?

我正在創建一個接受dictionary1並檢查是否有鍵作為值dictionary2存在的函數。

我試過使用dictionary2.isdisjoint(dictionary1)但這僅對檢查鍵有效。

如何檢查Python中價值的關鍵?

不知道這是否真的足夠大,可以放入單獨的函數中,但是無論如何,這是一個使用any()關鍵字的示例:

if any(k in d2.values() for k in d1.keys()):
    # do stuff

如果以下語句返回True (它將返回公共值),則:

set(dictionary1.keys()) & set(dictionary2.values())

說明:

  • dictionary1.keys()將給出dictionary1中的鍵列表

  • dictionary2.values()將給出dictionary2中的值列表

  • 將這兩個值轉換為set值,如果它們具有公共值,則最終將得到兩者之間的公共值。
 dictionary1 = {1:2, 2:3, 3:4} dictionary2 = {2:1, 2:3, 3:4} print set(dictionary1.keys()) & set(dictionary2.values()) 

輸出:

set([3])

這不是內置的操作。 您需要自己編寫邏輯。 您似乎正在使用python 3,因此類似以下的內容可能會起作用

>>> x = dict.fromkeys([0, 5, 10])
>>> y = {x: x for x in range(5)}
>>> print(x.keys().isdisjoint(y.values()))
False
>>> x.pop(0)
>>> print(x.keys().isdisjoint(y.values()))
True
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"

您的解決方案幾乎是正確的。 您必須添加not證明相反的內容(不相交==具有公共元素),並使用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))

輸出:

# 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM