[portland] Still Having List/Tuple Problems
Dylan Reinhardt
python at dylanreinhardt.com
Thu Apr 17 18:37:57 CEST 2008
The setdefault method returns what the dictionary has at the specified
key... but *sets* the value of that key first if no such key is found.
Thus, for this expression...
my_dict.setdefault(key, [])
...the return is always the list at my_dict[key] You can append to
this because it's always a list.
Hope that's helpful.
Dylan
On Thu, Apr 17, 2008 at 9:29 AM, Rich Shepard <rshepard at appl-ecosys.com> wrote:
> On Wed, 16 Apr 2008, Dylan Reinhardt wrote:
>
> >>>> 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
> > ...
>
> Dylan,
>
> Works perfectly for my report.
>
> I read in 'Python in a Nutshell' about the setdefault() method for
> dictionaries, but see nothing about extending that with .append(). Is this a
> short cut to adding the rightside values to each of the keys?
>
> Thanks for the lesson,
>
>
>
> Rich
>
> --
> Richard B. Shepard, Ph.D. | Integrity Credibility
> Applied Ecosystem Services, Inc. | Innovation
> <http://www.appl-ecosys.com> Voice: 503-667-4517 Fax: 503-667-8863
> _______________________________________________
> Portland mailing list
> Portland at python.org
> http://mail.python.org/mailman/listinfo/portland
>
More information about the Portland
mailing list