# CS 150 class example # Create histograms using dictionaries from any iterable data structure # (e.g., lists or strings) def get_counts(data): """ Count how many times each item occurs in data Args: data: Iterable collection of comparable items Returns: Dictionary of item : count """ counts = {} # Empty dictionary for item in data: counts[item] = counts.get(item,0) + 1 """ if item in counts: counts[item] += 1 # Increment count if present else: counts[item] = 1 """ return counts def print_counts(counts): """ Print out the counts from a dictionary Args: counts: Dictionary of item : count """ # Equivalent to print("Item\tCount") print("Item", "Count", sep="\t") for key, count in counts.items(): # Arguments to print are automatically converted to strings, the following is # equivalent to print(str(key) + "\t" + str(counts[key])) print(key, counts[key], sep="\t") def print_counts_sorted(counts): """ Print out the counts from a dictionary with keys in sorted order Args: counts: Dictionary of item : count """ # Need to convert set-like keys to list key_list = list(counts.keys()) key_list.sort() print("Item", "Count", sep="\t") for key in key_list: print(key, counts[key], sep="\t") #print_counts(get_counts("this is a string and strings are iterable")) #print_counts_sorted(get_counts("this is a string and strings are iterable")) #print_counts(get_counts("this is a list of strings and a list is iterable".split()))