[Tutor] Dictionaries

Jon Moore jonathan.r.moore at gmail.com
Thu Jan 26 10:03:07 CET 2006


Kent

Thanks! I have not come accross string formatting yet, but I can see how the
for statement works.

How would I modify this to just print either the values or keys?

Jon

On 26/01/06, Kent Johnson <kent37 at tds.net> wrote:
>
> Jon Moore wrote:
> > Hi
> >
> > Is there anyway to print informtation from dictionaries better than
> this?:
> >
> >  >>> pairs = {"Jon Moore": "Tony Moore",
> >          "Simon Nightingale": "John Nightingale",
> >          "David Willett": "Bernard Willet",
> >          "John Jackson": "Stuart Jackson",
> >          "James Southey": "Richard Southey",
> >          "William Forsythe": "Shaun Forsythe"}
> >  >>> print pairs.keys()
> > ['David Willett', 'Jon Moore', 'John Jackson', 'Simon Nightingale',
> > 'James Southey', 'William Forsythe']
> >  >>>
> >
> > Is there no way to make it a nice list as I want to print the keys and
> > values next to each other in a list such as:
>
> Of course there is :-)
>   >>> for father, son in pairs.iteritems():
>   ...   print '%-20s %s' % (father, son)
>   ...
> David Willett        Bernard Willet
> Jon Moore            Tony Moore
> John Jackson         Stuart Jackson
> Simon Nightingale    John Nightingale
> James Southey        Richard Southey
> William Forsythe     Shaun Forsythe
>
> pairs.iteritems() iterates over key, value pairs. The string formatting
> operations are very handy for formatted output.
> http://docs.python.org/lib/typesseq-strings.html
>
> Kent
>
> >
> > Jon Moore                  Tony Moore
> > Simon Nightingale       John Nightingale
> > David Willett               Bernard Willet
> > John Jackson             Stuart Jackson
> > James Southey          Richard Southey
> > William Forsythe        Shaun Forsythe
> >
> > For anyone who is wondering, it is to show father/son pairs. Next is to
> > add grandfathers *eek*.
> > --
> > Best Regards
> >
> > Jon Moore
> >
> >
> > ------------------------------------------------------------------------
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



--
Best Regards

Jon Moore
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060126/eb87db34/attachment.htm 


More information about the Tutor mailing list