[portland] Still Having List/Tuple Problems

Dylan Reinhardt python at dylanreinhardt.com
Thu Apr 17 01:20:44 CEST 2008


Oh cool!

Pretty soon Python will have a built-in object for *every* useful algo
I've ever learned.  :-)

Perhaps we're already there...

D.


On Wed, Apr 16, 2008 at 3:08 PM, Matt McCredie <mccredie at gmail.com> wrote:
>
> On Wed, Apr 16, 2008 at 1:48 PM, Dylan Reinhardt
>  <python at dylanreinhardt.com> wrote:
>  > Another approach to add to the pile:
>  >
>  >  >>> my_tuples = [('A',1),('A',2), ('A',3), ('A',4), ('B',1), ('B',2),
>  >  ('B',3), ('B',4)]
>  >  >>> grouper = {}
>  >  >>> for left, right in my_tuples:
>  >  ...         grouper.setdefault(left, []).append(right)
>  >  ...
>  >
>  >  now you have a dict with values groped by keys, as shown below...
>  >
>  >  >>> for key in grouper.keys():
>  >  ...        print key
>  >  ...        for value in grouper[key]:
>  >  ...             print '\t%s' % value
>  >  ...
>  >  A
>  >         1
>  >         2
>  >         3
>  >         4
>  >  B
>  >         1
>  >         2
>  >         3
>  >         4
>  >
>  >
>  >  HTH,
>  >
>  >  Dylan
>  >
>
>  Just to append to Dylan's response, you can get something similar with
>  `defaultdict`.
>
>  >>> from collections import defaultdict
>
> >>> my_tuples = [('A',1),('A',2), ('A',3), ('A',4), ('B',1), ('B',2),
>  ('B',3), ('B',4)]
>  >>> grouper = defaultdict(list)
>
> >>> for left, right in my_tuples:
>  ...     grouper[left].append(right)
>  ...
>
>  The rest remains the same.
>
>  Info on defaultdict: http://docs.python.org/lib/defaultdict-objects.html
>
>  Matt
>
>
> _______________________________________________
>  Portland mailing list
>  Portland at python.org
>  http://mail.python.org/mailman/listinfo/portland
>


More information about the Portland mailing list