creating lists based on parsed items
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Wed Jun 6 17:37:55 EDT 2007
En Wed, 06 Jun 2007 13:24:54 -0300, Jason White <jwhite at casl.umd.edu>
escribió:
> I am trying to do what (I think) should be fairly straightforward. I
> have a list of items that i want to sort into buckets. in item 1 of each
> line is the object I want to sort and in item 2 is the name of the
> bucket. I am making it dynamic however (so I don't know the bucket names
> in advance).
Forget about eval!
Use a dictionary: keys are bucket names, values a list containing all
associated items. You will find the setdefault method very useful.
d = {}
for each item, do: d.setdefault(bucket, []).append(item)
If you are using Python 2.5, use a defaultdict instead, the very first
example looks like what you want.
<http://docs.python.org/lib/defaultdict-objects.html>
--
Gabriel Genellina
More information about the Python-list
mailing list