[Python-ideas] Joining dicts again

spir denis.spir at gmail.com
Fri Feb 21 16:35:38 CET 2014


On 02/21/2014 10:40 AM, haael at interia.pl wrote:
>
> Hello
>
> I know this has been mangled thousand times, but let's do it once again.
>
> Why does Python not have a simple dict joining operator?
>
>  From what I read, it seems the biggest concern is: which value to pick up if both dicts have the same key.
> a = {'x':1}
> b = {'x':2}
> c = a | b
> print(c['x']) # 1 or 2?
>
> My proposal is: the value should be derermined as the result of the operation 'or'. The 'or' operator returns the first operand that evaluates to boolean True, or the last operand if all are False.
>
> So, provided we have 2 dicts 'a' and 'b' and c = a | b
>
> 1. If a key is not present in 'a' nor 'b', then it is not present in c.
> 2. If a key is present in 'a' and not in 'b', then c[k] = a[k].
> 3. If a key is present in 'b' and not in 'a', then c[k] = b[k].
> 4. If a key is present both in 'a' and 'b', then c[k] = a[k] or b[k].
>
>
> We could also naturally define dict intersection operator using the operator 'and' to pick values. The key would have to be present in both operands.
>
> Forgive me I wasn't able to read all previous discussions. Was this proposed before?

I don't see how this significantly differs from dict update, except that for you 
the first one to speak should win, instead of the opposite; so that you have to 
reverse the operands.

d


More information about the Python-ideas mailing list