And if you want all
from tabulate import tabulate
data_sites_and_birds_counted = [['A1', 28], ['A2', 32], ['A3', 1], ['A4', 0],
['A5', 10], ['A6', 22], ['A7', 30], ['A8', 19],
['B1', 145], ['B2', 27], ['B3', 36], ['B4', 25],
['B5', 9], ['B6', 38], ['B7', 21], ['B8', 12],
['C1', 122], ['C2', 87], ['C3', 36], ['C4', 3],
['D1', 0], ['D2', 5], ['D3', 55], ['D4', 62],
['D5', 98], ['D6', 32]]
# Create data variable. Easier to type the the long one
data = data_sites_and_birds_counted
# Create an empty dict to hold key, value data
# Create a counter variable to hold bird count
# Create empty list to use for getting total count per site
adict = {}
counter = 0
vals = []
# Create the key, values for our dict
# Key will be the letters A-D
# Value will be an empty list
for i in range(len(data)): # Get the length of data
letter = data[i][0][:1] # Get the letter of site using string slice
if letter not in adict.keys(): # Check if the letter is already in the dict if not set the key
adict[letter] = [] # Set letter value to empty list
if data[i][0].startswith(letter): # If the the starts with letter append the counts for that site
adict[letter].append(data[i][1])
# Loop through the dict to append totals
for key, value in adict.items():
vals.append(sum(value))
counter += sum(value)
# List comp to get the headers for list display
headers = [f'Station: {key.strip()}' for key in adict.keys()]
headers.append('All Stations') # Adding header for total count of all stations
vals.append(sum(vals)) # Getting total of all stations
# Using tabulate for display
print(tabulate([vals], headers, tablefmt='fancy_grid', numalign='center'))
print()
# Print out data without using tabulate
data = dict(zip(headers, vals))
for k, v in data.items():
print(k, v)
output:
Station: A 142
Station: B 313
Station: C 248
Station: D 252
All Stations 955