dict.updated

Rick Morrison ram at forefront-tech.No.Lunch.meat.com
Thu Jan 13 00:47:13 CET 2005


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.

 -- Or maybe I'm just lazy and picked up too many bad habits from
Javascript.

Rick


"Steven Bethard" <steven.bethard at gmail.com> wrote in message
news:dvKdnWal2sVXAXjcRVn-2g at comcast.com...
> Rick Morrison wrote:
> > Would there be any way to add a method to all dict objects that operated
> > like the .update() method, but also returned a reference to the updated
> > dict?
>
> Are you looking for updated() to parallel sorted(), where sorted()
> returns a *new* list?  I doubt you'll be able to rally much support for
> a method that changes an object and returns a reference to it -- check
> the archives to see these kind of things getting rejected over and over.
>
> Could you do something like:
>
> py> import itertools
> py> d1 = dict(a=1, b=2)
> py> d2 = dict(c=3, d=4)
> py> d3 = dict(itertools.chain(d1.iteritems(), d2.iteritems()))
> py> d3
> {'a': 1, 'c': 3, 'b': 2, 'd': 4}
>
> Steve





More information about the Python-list mailing list