[Python-ideas] Joining dicts again

Chris Angelico rosuav at gmail.com
Fri Feb 21 11:15:09 CET 2014


On Fri, Feb 21, 2014 at 8:40 PM,  <haael at interia.pl> wrote:
> 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?

If you can pick one of the dicts to "win", then you can use this notation:

c = dict(a, **b)

Anything in b will override a. It's short and a single expression
(unlike "c = a.copy(); c.update(b)"). It's not perfectly clear what's
happening, though, so it may warrant a comment.

ChrisA


More information about the Python-ideas mailing list