Space Python Loading Python…

Entries per level

Write the codeEasy 2 stages

At the end of every orbit the flight director gets one line about the log: how many entries of each level it had. A sudden jump in warnings says more than any single entry.

Count the entries per level, then make the count survive a level nobody planned for.

Count the entries of each level in a dict called counts, then print each level with its count:

INFO: 4
WARN: 3
ERROR: 1

Start with counts = {"INFO": 0, "WARN": 0, "ERROR": 0}. The level is the second word of an entry, line.split()[1], and counts[level] += 1 adds one to its counter.

Count per level
A dict of counters, any log

Finish stage 1 to unlock this stage.

The engineers switched on debug logging, and the starter code now stops with KeyError: 'DEBUG'. Count any level that turns up, and print the levels in alphabetical order, so the report looks the same whatever order they appear in:

DEBUG: 2
ERROR: 1
INFO: 4
WARN: 3

Start from an empty dict and use counts.get(level, 0) + 1. sorted(counts) gives the levels A to Z.

Count any level
Works for any log
You're not logged in, so your progress is kept in this browser only. Log in to save it, and to use hints and solutions.

Hints

Iterating Over Dictionary

iterating-over-dictionary.py
# How long a single day lasts on each planet, measured in Earth hours
day_hours = {
    "Mercury": 1408,
    "Venus": 5832,
    "Earth": 24,
    "Mars": 24.6,
    "Jupiter": 9.9,
}

# A plain for loop walks the keys
for planet in day_hours:
    print("Planet:", planet)

# .values() walks the values instead
total = 0
for hours in day_hours.values():
    total = total + hours
print("All five days added together:", total, "hours")

# .items() hands you the key and the value at the same time
for planet, hours in day_hours.items():
    print(f"{planet}: one day is {round(hours / 24, 2)} Earth days")

# sorted() walks the same keys in a different order
for planet in sorted(day_hours):
    print(planet, "->", day_hours[planet], "hours")
Open the full example
script.py
PythonLn 1, Col 1Spaces: 4
Loading the Python environment…

Separate arguments with commas. They're passed on every Run as sys.argv[1:].