100 days of code: Day 14 - dictionaries

Last modified on 2020-06-22

Source: 100-days-of-code.

A dictionary in Python is a collection of key-value pairs. I created a program - sol_sys_dict.py - that defines a dictionary about our solar system, adds and modifies key-value pairs, nests lists in a dictionary, and loops through the information stored in a dictionary for display …

#!/usr/bin/env python3

title = 'Solar System'
sol_sys = {'Age': '4.568 billion years',}       # dictionary
stars = ['Sun',]                                # list
known_planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 
                'Uranus', 'Neptune',]

# add and delete to a dictionary
sol_sys['Location'] = ('Local Interstellar Cloud, '
                        + 'Local Bubble, Orion–Cygnus Arm, '
                        + 'Milky Way')          # add new key-value pair
sol_sys['System mass'] = '8.0088 Solar masses'
sol_sys['Nearest stars'] = ('Proxima Centauri (4.25 ly), '
                            + 'Alpha Centauri (4.37 ly)')
sol_sys['System mass'] = '1.0014 Solar masses'  # modify value
sol_sys['Stars'] = stars[0]
sol_sys['Known planets'] = known_planets        # nest a list of items
sol_sys['Known wormholes'] = 'Tumbledown 88'
del sol_sys['Known wormholes']                  # remove key-value pair

print("=" * len(title))
# loop through the dictionary
for key, value in sol_sys.items():
    if key == 'Stars':
        print(f"{key}: " + str(len(stars)) + f" ({value})")
    elif key == 'Known planets':
        # Suppress the newline using (x, end="")
        print(f"{key}: " + str(len(known_planets)) + " (", end="")
        for planet in sol_sys['Known planets']:
            if planet == 'Neptune':
                print(f"{planet}, ", end="")
        print(f"{key}: {value}")

# get() method sets default value if requested key does not exist
wormhole = sol_sys.get('Known wormholes', 
                        '*Presence of wormholes remain unconfirmed')
print(f"Known wormholes: {wormhole}")

Run …

$ ./sol_sys_dict.py 

Solar System
Age: 4.568 billion years
Location: Local Interstellar Cloud, Local Bubble, Orion–Cygnus Arm, Milky Way
System mass: 1.0014 Solar masses
Nearest stars: Proxima Centauri (4.25 ly), Alpha Centauri (4.37 ly)
Stars: 1 (Sun)
Known planets: 8 (Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune)
Known wormholes: *Presence of wormholes remain unconfirmed

Happy hacking!