user2205015
user2205015

Reputation: 85

Python Print Formatting

dict={'algorithm':'user1','datastr':'user2','hashing':'user3'}
def forums(dict):
    header = ("SubForums","Created By")
    dict_list=dict.items()
    dict_list.insert(0,header)
    i=0
    col_width = max(len(word) for row in dict_list for word in row) + 2 # padding
    for row in dict_list:
            print str(i+1)+"."+"".join(word.ljust(col_width) for word in row)

I want to print it like this:

SubForums   Created By  
1.Algorithm User1     
2.Hash      user2           
3.datastr   user3

It currently prints like dis:

  1.SubForums   Created By  
  2.Algorithm   User1     
  3.Hash        user2           
  4.datastr     user3

Can anyone please correct my code and help me out. Thank You in advance.

Upvotes: 0

Views: 462

Answers (1)

lynn
lynn

Reputation: 10784

def forums(d):
    dict_list = [('Subforums', 'Created by')]
    for i, (k, v) in enumerate(d.items(), 1):
        k = '{0}. {1}'.format(i, k)
        dict_list.append((k, v))

    col_width = max(len(word) for row in dict_list for word in row) + 2 # padding

    for row in dict_list:
            print ''.join(word.ljust(col_width) for word in row)

(Note how I've changed dict to d: using a built-in function's name as a variable is a bad idea!)

Upvotes: 2

Related Questions