[portland] Still Having List/Tuple Problems

Matt McCredie mccredie at gmail.com
Thu Apr 17 00:08:51 CEST 2008


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


More information about the Portland mailing list