On 23/02/2014 13:31, haael@interia.pl wrote:
@Steven D'Aprano
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
All solutions provided by you are not one-liners. Every requires at least 2 lines of code and is an imperative-style code block, instead of a simple expression.
Excellent as it makes the code easier to read. Let's leave things like that.
I would really like to have a simple dict joining _expression_ that can be inserted everywhere I just need.
I wouldn't. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com