[Python-ideas] Joining dicts again

haael at interia.pl haael at interia.pl
Fri Feb 21 10:40:51 CET 2014


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?

Thanks
haael


More information about the Python-ideas mailing list