[Python-ideas] Joining dicts again

Cory Benfield cory at lukasa.co.uk
Fri Feb 21 11:17:38 CET 2014


On 21 February 2014 09:40,  <haael at interia.pl> wrote:
> 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].

This seems to me to be exactly the same as dict.update():

a = {'x': 1}
b = {'x': 2}

c = b.copy()
c.update(a)

I'd be very reluctant to overload the bitwise-or operator to mean
'dictionary merging'. It's just not totally obvious to me that this is
what would happen.


More information about the Python-ideas mailing list