This question is inspired by this question. I’d like to get a dictionary from a list of dictionaries that should contain all key/value pairs from all dictionaries that are either only contained once, or where all dictionaries agree on the associated value. Example (taken from the aforementioned posting):
dicts = [dict(a=3, b=89, d=2), dict(a=3, b=89, c=99), dict(a=3, b=42, c=33)]
print dict_itersection(dicts)
should yield
{'a': 3, 'd': 2}
My current implementation looks like this:
import collections
def dict_intersection(dicts):
c=collections.defaultdict(set)
for d in dicts:
for a, b in d.iteritems():
c[a].add(b)
return {a: next(iter(b)) for a, b in c.iteritems() if len(b) == 1}
So my question: Can this be done more elegantly?
Sidequestion: can next(iter(b)) be done better without modification of the underlying dictionary (i.e. not b.pop())?
All solutions so far assume that all dictionary values are hashable. Since the code won’t get slower and only little more complex without this assumption, I’d drop it. Here’s a version that works for all values that support
!=:The set
conflictingwill only contain dictionary keys, which will always be hashable.