[Tutor] Re: Tutor] A nicer output...
Alexandre Ratti
alex@gabuzomeu.net
Tue, 02 Apr 2002 10:44:01 +0200
Hi Nicole,
At 18:55 01/04/2002 -0500, you wrote:
>From: Nicole Seitz <nicole.seitz@urz.uni-hd.de>
>Date: Mon, 1 Apr 2002 21:04:08 +0200
>Subject: [Tutor] A nicer output...
> >Yes, pprint is just a quick way to display the content of a dictionary or
> >list. For a nicer output, you need to write some more code.
>
>Ok, I wrote some code , but the result is still not satisfactory:
>
>WORD: IN LINE(S):
>===================================================
>MarkUp [338]
>SoftQuad [335]
>AnyPoint [479, 478, 477]
>Is there a better way to get a nicely formatted output?(I 'm sure there is
>one..)
How do you want to format the list? For instance, you may want to separate
the line numbers with commas. Take a look at the join() method of strings.
>>> toto = [1, 2, 3, 4]
# First, let's convert the list content from integers to strings. Here we
use a
# feature called list comprehension (new in Python 2), but you can do that
# with a 'for' loop (left as an exercice :-)
>>> titi = [str(x) for x in toto]
>>> print titi
['1', '2', '3', '4']
# Now, let's join the list with a comma and a space
>>> print ", ".join(titi)
1, 2, 3, 4
>Oh, almost forgot to add my code:
>
> print "WORD:\t\t\tIN LINE(S): "
> print "==================================================="
>
> for key in wordDict.keys():
>
> print key,"\t\t\t",uniq(wordDict[key])
To output values, you can also use the "%" idiom:
>>> titi = 1
>>> toto = "truc"
>>> outputTemplate = "First value: %i - Second value: %s"
>>> print outputTemplate % (titi, toto)
First value: 1 - Second value: truc
This is useful to format output strings in a complex way. As you guess, %i
is the placeholder for an integer and %s is a placeholder for a string.
There are codes for other data types.
> >>How come that the words in the output are alphabetically ordered?
>
> >I was surprised too. The pprint function (prettyprint) seems to sort the
> >output by default.
>
>Well, if I don't want to use pprint, how can I then sort my dictionary
>(alphabetically)? I read somewhere about sorting dictionaries, but can't find
>it right now.Hope you can help!
You can copy the keys to a list, sort the list and use it to iterate on the
dictionary content.
Eg. :
keyList = wordDict.keys()
keyList.sort()
for key in keyList:
print key, wordDict[key]
Cheers.
Alexandre