[Python-talk] Pythonic approach to populating a dict

Cole Tuininga colet at code-energy.com
Sun Jul 22 16:59:56 EDT 2007


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/
	



More information about the Python-talk mailing list