kjo*_*kjo 5 python dictionary intersection
我想要一个实现intersection_update方法的字典类,在精神上类似于dict.update但仅将更新限制为调用实例中已存在的那些键(参见下面的一些示例实现).
但是,根据Wheel Reinvention Avoidance的精神,在我开始实现(以及编写测试等)具有这种附加功能的映射类之前,这样的事情是否已经存在于一个或多或少的标准模块中?
要清楚,intersection_update我想到的方法会做这样的事情:
def intersection_update(self, other):
for k in self.viewkeys() & other.viewkeys():
self[k] = other[k]
Run Code Online (Sandbox Code Playgroud)
...虽然实际的实现可能会尝试一些可能的优化,例如:
def intersection_update(self, other):
x, y = (self, other) if len(self) < len(other) else (other, self)
for k in x.iterkeys():
if k in y:
self[k] = other[k]
Run Code Online (Sandbox Code Playgroud)
编辑:在这篇文章的原始版本中,我曾写过"或者,有没有一个标准的Python成语,不需要实现[带有一个intersection_update方法]?",但我几乎立即删除它,因为,经过进一步的反思,我意识到这是一个弱回答的邀请,因为我已经足够了解Python语言的"核心",以确定不存在这样的习语,至少没有一个能够与优势相匹配的(普遍性,易读性,易于打字)一种专用方法.
尝试这个:
def dict_intersection(d1, d2):
return dict((key, d2[key] or d1[key]) for key in frozenset(d1) & frozenset(d2))
Run Code Online (Sandbox Code Playgroud)
或者,对于 python 版本 >= 2.7:
def dict_intersection(d1, d2):
return {key: d2[key] or d1[key] for key in d1.viewkeys() & d2.viewkeys()}
Run Code Online (Sandbox Code Playgroud)