Learning Scientific Programming with Python (2nd edition)
E4.7: A simple database of astronomical objects
A Python dictionary can act as a kind of simple database. The following code stores some information about some astronomical objects in a dictionary of tuples, keyed by the object name, and manipulates them to produce a list of planet densities.
import math
# Mass (in kg) and radius (in km) for some astronomical bodies
body = {
"Sun": (1.988e30, 6.955e5),
"Mercury": (3.301e23, 2440.0),
"Venus": (4.867e24, 6052.0),
"Earth": (5.972e24, 6371.0),
"Mars": (6.417e23, 3390.0),
"Jupiter": (1.899e27, 69911.0),
"Saturn": (5.685e26, 58232.0),
"Uranus": (8.682e25, 25362.0),
"Neptune": (1.024e26, 24622.0),
}
planets = list(body.keys())
# The sun isn't a planet!
planets.remove("Sun")
def calc_density(m, r):
"""Returns the density of a sphere with mass m and radius r."""
return m / (4 / 3 * math.pi * r**3)
rho = {}
for planet in planets:
m, r = body[planet]
# calculate the density in g/cm3
rho[planet] = calc_density(m * 1000, r * 1.0e5)
for planet, density in sorted(rho.items()):
print(f"The density of {planet} is {density:3.2f} g/cm3")
sorted(rho.items())
returns a list
of the rho
dictionary's key-value pairs, sorted by key.
The output is:
The density of Earth is 5.51 g/cm3
The density of Jupiter is 1.33 g/cm3
The density of Mars is 3.93 g/cm3
The density of Mercury is 5.42 g/cm3
The density of Neptune is 1.64 g/cm3
The density of Saturn is 0.69 g/cm3
The density of Uranus is 1.27 g/cm3
The density of Venus is 5.24 g/cm3