How to print columns

10 Mar 2024

To print neat columns in Python use str.format():

d = dict(apples=4, oranges=27, kiwi=108)
max_width = str(max([len(k) for k in d]))
column = "{:>" + max_width + "} {:>" + max_width + "}"
print(column.format("Fruit", "Count"))
for key in sorted(d.keys()):
    print(column.format(key, d[key]))

Output:

  Fruit   Count
 apples       4
   kiwi     108
oranges      27