[Python-talk] Pythonic approach to populating a dict

Bob Erb bob.erb at gmail.com
Sun Jul 22 19:12:45 EDT 2007


<python-code>

class Man:
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return 'man named ' + self.name

list_of_men = [Man('Bob'), Man('Bill'), Man('Randy')]

dict = dict(zip([man.name for man in iter(list_of_men)], list_of_men))

print dict

</python-code>

Correct?

On 7/22/07, Cole Tuininga <colet at code-energy.com> wrote:
>
> As I find myself coding in "perlland" these days, I often wonder if
> Python has a way to do things that I've come to take for granted in
> perl.  In this case, I'm looking to populate a dictionary.
>
> I have a list of objects, and I would like to turn it into a dictionary
> where the key is a particular attribute of the object.
>
> In perl, I could do something like this:
>
> $dict = { map {$_->{'attribute'} => $_} @list_of_objects };
>
> This would give me back a reference to a hash(dict) where the keys are
> the 'attribute' value from each object.  This obviously presupposes that
> there is either a unique mapping of this attribute to an object, or that
> I don't care about the fact that I'd lose duplicates.
>
> In any case, I could certainly accomplish this in python by doing
> something like:
>
> my_dict = {}
> for item in obj_list:
>         my_dict[item.attribute] = item
>
> but I was wondering if there is a Python equivalent to map that will
> yield a dictionary instead of a list?
>
> Just curious.  :)
>
> --
> A: Yes.
> > Q: Are you sure?
> >> A: Because it reverses the logical flow of conversation.
> >>> Q: Why is top posting annoying in email?
>
> Cole Tuininga
> colet at code-energy.com
> http://www.code-energy.com/
>
>
> _______________________________________________
> Python-talk mailing list
> Python-talk at dlslug.org
> http://dlslug.org/mailman/listinfo/python-talk
>


More information about the Python-talk mailing list