簡體   English   中英

python詞典匹配兩個詞典中的鍵值

[英]python dictionary match key values in two dictionaries

在下面顯示的詞典中,我想檢查aa中的鍵是否與bb中的鍵匹配,並且對應的值是否與bb匹配。是否有更好的方法來編寫此代碼

  aa = {'a': 1, 'c': 3, 'b': 2}
  bb = {'a': 1, 'b': 2}

  for k in aa:
    if k in bb:
      if aa[k] == bb[k]:
         print "Key and value bot matches in aa and bb"

使用集合查找所有等價物:

for (key, value) in set(aa.items()) & set(bb.items()):
    print '%s: %s is present in both aa and bb' % (key, value)

&運算符在這里為您提供兩組交集 ; 或者你可以寫:

set(aa.items()).intersection(set(bb.items()))

請注意,這確實創建了兩個dicts的完整副本,因此如果這些非常大,那么這可能不是最好的方法。

一個捷徑只是測試密鑰:

for key in set(aa) & set(bb):
    if aa[key] == bb[key]:
        print '%s: %s is present in both aa and bb' % (key, value)

在這里,您只需復制每個字典的鍵以減少內存占用。

使用Python 2.7時,dict類型包含直接創建所需集的其他方法

for (key, value) in aa.viewitems() & bb.viewitems():
    print '%s: %s is present in both aa and bb' % (key, value)

這些是技術上的字典視圖,但出於這個問題的目的,它們的行為相同。

這可以寫成一行all

all(bb[k] == v for k, v in aa.iteritems() if k in bb)

它也是更具聲明性的方法,可能更好地傳達意圖。

如果要迭代所有匹配的鍵/值對,可以使用

for key, value in aa.viewitems() & bb.viewitems():
    ...

(Python 2.7)

暫無
暫無

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

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