import csv from collections import defaultdict def get_list(animals_file, toys_file, houses_file): """ Join 3 csv files using to a column with name "uid" """ # index will be a dictionary of the form: # { uid1:{ "animal":animal1, "toy":toy1, "house":house1 }, uid2:{ ... } } index = defaultdict(dict) with open(animals_file) as f_animals: reader = csv.DictReader(f_animals) for row in reader: unique_index = int(row["uid"]) # note that we don't have to check that the dictionary at 'index[unique_index]' already exists as we use defaultdict index[unique_index]["animal"] = row["animal"].strip() with open(toys_file) as f_toys: reader = csv.DictReader(f_toys) for row in reader: unique_index = int(row["uid"]) index[unique_index]["toy"] = row["toy"].strip() with open(houses_file) as f_houses: reader = csv.DictReader(f_houses) for row in reader: unique_index = int(row["uid"]) index[unique_index]["house"] = row["house"].strip() # we want to return a list instead of a dict, so we remove the indices return index.values() default_template = "the {animal} plays with the {toy} in the {house}" def out_text(mylist, template= default_template, pre="", post=""): """ return text from a list of dictionaries according to a template """ return pre+"\n"+"\n".join(template.format(**my_dict) for my_dict in mylist)+"\n"+post if __name__ == '__main__': my_list = get_list("animals.csv", "toys.csv", "houses.csv") print(out_text(my_list)) table_template = "| {animal:^20} | {toy:^20} | {house:^30} |" print(out_text(my_list,table_template,pre="_"*80,post="_"*80)) html_template = " {animal:^20} {toy:^20} {house:^30} " print(out_text(my_list,html_template,pre="",post="
"))