def complement(gender): if gender == "M": return "F" else: return "M" def lastLetterIndex(): # Open the file and extract all the information into # a giant list f = open("babyNames.txt", "r") L = [] for line in f: L.append(line.strip().split(",")) f.close() # Initialize dictionary D = {} # Each lower case letter is a key for ch in range(ord("a"), ord("z")+1): D[chr(ch)] = [] # The value of each such key is a list of # 134 dictionaries, initially empty for i in range(134): D[chr(ch)].append({}) # Populate dictionary with elements from L for record in L: year = int(record[0]) name = record[1] gender = record[2] freq = int(record[3]) lastLetter = name[len(name)-1] if name not in D[lastLetter][year-1880]: D[lastLetter][year-1880][name] = [(gender, freq), (complement(gender), 0)] D[lastLetter][year-1880][name].sort() elif gender == "F": D[lastLetter][year-1880][name][0] = (gender, freq) else: D[lastLetter][year-1880][name][1] = (gender, freq) return D