Day 69: Make Good Looking Tables With PrettyTable (Module)

 

Scripts running in the shell are pretty cool. But sometime you want to display tables that have no real format.

 

The module PrettyTable generates some – well pretty – tables with just a couple of lines.

 

The script takes a dictionary with the sizes of all planets in the solar system.

 

It exports it in a PrettyTable in descending order.

 

# PrettyTable module
# Create handsome tables in your shell
from prettytable import PrettyTable

planets = {"Mercury" : "4879",
        "Venus" : "12104",
        "Earth" : "12756",
        "Mars" : "6779",
        "Jupiter" : " 142984",
        "Saturn" : "120536",
        "Uranus" : "50724",
        "Neptune" : "49244"
        }

# create the table with two colums
size_table = PrettyTable(["Planet", "Diameter (km)"])

# go over every planet in dict and add a row for each
for item in planets:
    size_table.add_row([item, planets[str(item)]])

# sort planets from big to small
size_table.sort = True

print(size_table)

The output looks like this: