-1
for k, v in country_cap_dict.items():
    print "%s : %s" % (k,v)

my for loop is giving me output like this

           US : Washington
           Canada : Ottawa
           Germany: Berlin
           France : Paris
           England : London
           Switzerland : Bern
           Austria : Vienna
           Netherlands : Amsterdam

How can I improve readability so that output looks like:

           US :          Washington
           Canada :      Ottawa
           Germany:      Berlin
           France :      Paris
           England :     London
           Switzerland : Bern
           Austria :     Vienna
           Netherlands : Amsterdam
0

2 Answers 2

1

You can use C style string formatting in Python:

http://www.diveintopython.net/native_data_types/formatting_strings.html

So, you can specify how much padding to give.

'%-24s %s' % ("US", "Washington")
'%-24s %s' % ("Brazil", "Washington") //padded to 24 spaces width between

Result:

'US                       Washington'
'Brazil                   Washington'
Sign up to request clarification or add additional context in comments.

1 Comment

It just shifts all values by the distance of 24 spaces. I don't want that. I want all the values of the dictionary to be properly alligned. Say in one vertical column like I mentioned in my post.
0

Add '\t' after the first %s like so:

print "%s : \t%s" % (k,v)

1 Comment

Use the formatting operator with field widths, it's much more flexible.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.