Dictionary, iterate & update objects
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Mon Dec 18 06:21:39 EST 2006
jansenh a écrit :
> hi comp.lang.python.
>
> I need some newbe advice on idiomatic use of Python dictionaries.
>
> I have service with a dictionary which holds a bunch of objects as
> values, and an ID as key to each object. Then I want to change an
> objects state based on its key.
class MyObj(object):
def __init__(self, foo):
self.foo = foo
objs = {
'foo': MyObj('foo'),
'bar', MyObj('bar'),
}
objs['foo'].foo = 42
for key, obj in objs:
print "%s : %s" % (key, obj.foo)
> The way I am doing this now is by using
> 'fromkeys' and copying my object over in a temporary dictionary, then
> manipulating the object, and then I do an 'update' back to the main
> dictionary.. :-0
My my my...
> There has to be a smarter way?
Indeed. Usually, with Python, "smarter" => "simplest"
HTH
More information about the Python-list
mailing list