[Python-ideas] Joining dicts again
Chris Angelico
rosuav at gmail.com
Sun Feb 23 15:21:47 CET 2014
On Mon, Feb 24, 2014 at 12:31 AM, <haael at interia.pl> wrote:
> dict_default = {'a':None, 'b':[]}
> fun(**(funA(dict_default) | funB(dict_default))
>
All you need is a shorter name for your function and the job's done.
Since it'll be local to your module anyway, it doesn't need the long
and verbose name. Here's Steven's #3, implemented as a function:
def merge(a, b):
"Merge two dicts using 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
Or you could make it shorter thus:
def merge(a, b):
"Merge two dicts using the 'or' operator
c = a.copy()
for key, value in b.items():
c[key] = c.get(key) or value
Then your code is:
dict_default = {'a':None, 'b':[]}
fun(**merge(funA(dict_default), funB(dict_default)))
That's it!
ChrisA
More information about the Python-ideas
mailing list