Steven Bethard steven.bethard at gmail.com
Wed Jan 12 19:49:43 EST 2005

Rick Morrison wrote:
> I could live with creating a new dict, sure (although it seems wasteful). I
> realize that something like this probably doesn't stand a chance of ever
> making it into the std library for what might be called "philosophical"
> reasons. I just want it for me (my personal philosophy runs more to the
> pragmatic -- well at least for coding).
> I suppose the in-place version would be more along the lines of:
>>>>def updated(d, updates):
> ...        d.update(updates)
> ...        return d
> ...
>>>>[updated(d, {'c':3}) for d in [{'a':1, 'b':2}, {'x':10, 'y':'11'}]]
> [{'a': 1, 'c': 3, 'b': 2}, {'y': '11', 'x': 10, 'c': 3}]
> But I'd like to put the "updated" method on the "dict" object, which is what
> I can't seem to figure out.
> Yeah I know that's "bad", but to my mind so is polluting the global
> namespace with the "updated" function.

You could do something like:

py> class dict(dict):
...     def updated(self, *args, **kwds):
...         self.update(*args, **kwds)
...         return self
py> [d.updated(c=3) for d in [dict(a=1, b=2), dict(x=10, y=11)]]
[{'a': 1, 'c': 3, 'b': 2}, {'y': 11, 'x': 10, 'c': 3}]

It'd mean you'd have to create all your dicts with the dict constructor 
instead of {} though.


More information about the Python-list mailing list