[Python-talk] Pythonic approach to populating a dict

Kent Johnson kent37 at tds.net
Sun Jul 22 22:20:11 EDT 2007


Cole Tuininga wrote:
> 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?  

First of all, the above code does result in a dict - my_dict is a dict. 
It can be written more compactly as
   my_dict = dict((item.attribute, item) for item in obj_list)

which creates the dict from a sequence of key, value pairs.

Kent


More information about the Python-talk mailing list