accessing an object instance by only having one of its attribute values

Paul McGuire ptmcg at austin.rr.com
Sun Jul 8 20:29:53 EDT 2007


On Jul 8, 2:11 pm, mshiltonj <mshilt... at gmail.com> wrote:
> On Jul 8, 2:18 pm, feli... at gmail.com wrote:
>
> > Hello all,
>
> > Imaybe someone can help me with this question.
> > Is there a direct way of accessing an object instance, if all I know
> > is the value of one of its attributes?
> > The object is part of a list of objects, and I would like to pick the
> > object directly by using this attribute value, instead of going
> > through the list and checking if each objects attribute value is the
> > one I am looking for.
>
> > Thank you in advance
>
> I'd set up a dict as a lookup table, assuming the attribute values are
> unique per object.
>
> list_of_objects = (obj1, obj2, obj3, obj4);
>
> obj_lookup_by_attr = {};
>
> for obj in list_of_objects:
>    obj_lookup_by_attr.set(obj.attr, obj)
>
> [...]
>
> obj = obj_lookup_by_attr.get(attr_val, None);
>
> if (obj):
>    [...]

I have some comments on the Pythonicity of your suggestions.  Same
assumption, object attr is a unique key of some sort.  How to create
the dict of objects, and how to retrieve an object by key.

-- Paul


list_of_objects = (obj1, obj2, obj3, obj4);

# creating a dict by initializing to empty, and then looping
# through input list and adding items one at a time
obj_lookup_by_attr = {};
for obj in list_of_objects:
    #obj_lookup_by_attr.set(obj.attr, obj)
    # why use set for this?  why not just this:
    obj_lookup_by_attr[obj.attr] = obj

# or even better might be to use a generator expression to create a
# sequence of tuples, and call the dict constructor - a good idiom to
# learn
obj_lookup_by_attr = dict( (obj.attr,obj) for obj in list_of_objects )

[...]

obj = obj_lookup_by_attr.get(attr_val, None);

# oh woe if obj is an instance of a class that defines special
# true/falseness - obj might be a real object, but evaluates to false
#
#if (obj):
#
# much better to test this way
# (and NEVER test using "if obj != None:" - this is wasteful
# nonsense, since None is a singleton)
if obj is not None:
   [...]




More information about the Python-list mailing list