[Python-ideas] Joining dicts again
Steven D'Aprano
steve at pearwood.info
Fri Feb 21 23:57:34 CET 2014
On Fri, Feb 21, 2014 at 05:05:58PM +0100, Markus Unterwaditzer wrote:
[...]
> It seems that everybody misses the part of the OP where he states that
> conflict resolution shouldn't happen via "one dict wins" but rather with
> the "or"-operator.
I certainly did :-(
So we have *at least* four different ways to merge dictionaries a and b:
# 1: a wins
c = b.copy()
c.update(a)
# 2: b wins
c = a.copy()
c.update(b)
# 3: choose a winner according to the `or` operator
c = a.copy()
for key, value in b.items():
if key in c:
c[key] = c[key] or value
else:
c[key] = value
# 4: keep both, in a list of 1 or 2 items
c = {key:[value] for key, value in a.items()}
for key, value in b.items():
if key in c and value != c[key][0]:
c[key].append(value)
else:
c[key] = [value]
The first three are special cases of a more general case, where
you have a "decision function" that takes two values (one from dict a
and the other from dict b) and decides which one to keep. Case 1 ("a
always wins") would use `lambda x,y: x`, case 2 ("b wins") would use
`lambda x,y: y` and case 3 would use operator.or_.
The question is, why should any one of these be picked out as so
obviously more useful than the others as to deserve being a dict method
or operator support?
--
Steven
More information about the Python-ideas
mailing list