[英]How do I return a new dictionary if the keys in one dictionary, match the keys in another dictionary?
[英]How do I find the keys in one dictionary that do not have a counterpart in another dictionary?
在 Python 中,如何在一本字典中找到在另一本字典中沒有對應項的鍵? 實際問題是,我有一本注冊人的字典和一本他們日常參與的字典,我試圖找到注冊但沒有參與的人,或者在注冊字典中而不在參與字典中的人。
在 Python 食譜中,我找到了很好的代碼,用於交集注冊和參與,或兩個字典的交集:
print "Intersection: ", filter(enrollments.has_key, participation.keys())
但我無法弄清楚如何將此邏輯擴展到正面(?)的情況。 我試過在partition.keys() 前面放一個not,但出現錯誤。 有沒有辦法將過濾器中的邏輯擴展到我的問題或另一種完全解決它的方法?
使用鍵上的集合來找出差異:
>>> P = dict(zip('a b c d'.split(),[1,2,3,4]))
>>> E = dict(zip('a b e f'.split(),[6,7,8,9]))
>>> set(P)-set(E)
{'d', 'c'}
>>> set(E)-set(P)
{'f', 'e'}
此外,您可以使用字典理解。 這是一種在字典中映射函數和/或過濾內容的方法。 語法意味着為字典的項目中的每個鍵和值返回鍵:值對,其中鍵不在另一個字典中:
>>> {k:v for k,v in P.items() if k not in E}
{'d': 4, 'c': 3}
>>> {k:v for k,v in E.items() if k not in P}
{'f': 9, 'e': 8}
您可以使用lambda
作為過濾器的第一個參數。
print "Intersection: ", filter(lambda x:x not in participation, enrollments)
在 Python 3 中, dict.keys()
為您提供了字典中鍵的類似集合的視圖,因此這樣做很簡單:
>>> enrolled = {'steve': 0, 'mike': 42, 'judy': 100}
>>> participated = {'judy': 5, 'mike': 10}
>>> enrolled.keys() - participated.keys()
{'steve'}
在 Python 2 中,將.keys()
替換為.viewkeys()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.