-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
tryPy
  • 71
  • 1
  • 11

2 Answers2

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'
Calvin Froedge
  • 16,135
  • 16
  • 55
  • 61
  • 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. – tryPy Sep 11 '14 at 17:26
0

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

print "%s : \t%s" % (k,v)
tomer.z
  • 1,033
  • 1
  • 10
  • 25