On Sat, Feb 12, 2011 at 9:08 AM, Martin De Kauwe <mdeka...@gmail.com> wrote:
> Hi,
>
> Is there a better way to unpack more than one dictionary in a function
> than...
>
> def unpack_dicts(f):
>    def wrapper(*old_dicts):
>        dict={}

I wouldn't call the variable "dict" since that clashes with the name
of the built-in type.

>        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)

Aside from slight variants on this approach, no, there's not really a
better way to do it.
There's no built-in way to do it because different users might want
different dict merging algorithms, such as:
- multiple values for the same key is an error
- multiple values for the same key are combined into a list/set of values
- entries in earlier dicts clobber those in later dicts
- entries in later dicts clobber those in earlier dicts

Python has "In the face of ambiguity, refuse the temptation to guess."
and "Explicit is better than implicit." among its design principles,
and hence provides no default solution here, requiring the user to
specify the behavior explicitly by doing the merging themselves.

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to