过滤字典中的项目

时间:2018-02-16 19:19:59

标签: python python-3.x

我想从一个字典中过滤项目,其中该字典包含另一个字典的项目。所以,假设我有两个字典dict1dict2其中

dict1  = {
    1:{'account_id':1234, 'case':1234, 'date': 12/31/15, 'content': 'some content'},
    2:{'account_id':1235, 'case':1235, 'date': 12/15/15, 'content': 'some content'}
}
dict2 = {
    1:{'account_id':1234, 'case':1234, 'date': 12/31/15, 'content': 'some different content'},
    2:{'account_id':4321, 'case':4321, 'date': 6/12/15, 'content': 'some different content'},
    3:{'account_id':1235, 'case':1235, 'date': 12/15/15, 'content': 'some different content'}
}

我想在account_id,case和date上匹配,并将输出作为第三个字典,其中dict2的匹配条目为1和3。

out = {
    1:{'account_id':1234, 'case':1234, 'date': 12/31/15, 'content': 'some different content'},
    2:{'account_id':1235, 'case':1235, 'date': 12/15/15, 'content': 'some different content'}
}

我将如何做到这一点?我使用的是Python 3.5

1 个答案:

答案 0 :(得分:2)

那么,我相信这就是你要找的东西:

from itertools import count
from operator import itemgetter
# Set the criteria for unique entry (prevents us from needing to write this twice)
get_identifier = itemgetter("account_id","case","date")

# Create a set of all unique items.
unique_entries = set(map(get_identifier, dict1.values()))

# Get all entries that match one of the unique entries
matched_entires = (d for d in dict2.values() if get_identifier(d) in unique_entries)

# Recreate a new dict together with a counter for items.
out = dict(zip(count(1), matched_entires))

有关count()itemgetter()的详细信息,请参阅各自的文档。

使用集合和生成器理解可确保最高级别的效率。