Unpacking multiple dictionaries in a function?
Peter Otten
__peter__ at web.de
Sat Feb 12 13:28:56 EST 2011
Martin De Kauwe wrote:
> Is there a better way to unpack more than one dictionary in a function
> than...
>
> def unpack_dicts(f):
> def wrapper(*old_dicts):
> dict={}
> for d in old_dicts:
> dict.update(d)
> return f(**dict)
> return wrapper
>
> @unpack_dicts
> def some_func(a=None, b=None, c=None):
> print a, b, c
>
> d1 = {'a': 20.0, 'b': '-1'}
> d2 = {'c': 33.0}
>
> some_func(d1, d2)
>
> thanks
If you had shown a solution involving
>>> dicts = [dict(a=1, b=2, c=3), dict(a=10, b=20, z=40), dict(a=100,
t=500)]
>>> reduce(lambda a, d: a.update(d) or a, dicts, {})
{'a': 100, 'c': 3, 'b': 20, 't': 500, 'z': 40}
I would have pointed out your approach. So yes, I think you have already
found the best solution.
More information about the Python-list
mailing list