[Tutor] Dictionaries
Kent Johnson
kent37 at tds.net
Thu Jan 26 02:23:04 CET 2006
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
More information about the Tutor
mailing list