""" Felix Muzny DS 2000 Lecture 15 November 1, 2024 Dictionary experiments """ import random # do not use dict as a variable name # it is a function (like sum()) -- dict() def pretty_print_dict(passed_dict): """ prints out the dictionary in format key : value :param passed_dict: dict to be printed :return: none """ for key, value in passed_dict.items(): print(key, ":", value) def count_rolls(num_rolls): """ Count the number of times each value was rolled on a six-sided die, mapping value rolled to number of times it was rolled example: 10 -> {1:3, 2:1, 4:2, 5:3, 6:1} :param num_rolls: int number of rolls to make :return: dictionary of ints to ints """ # initialize our dict rolls = {} # 1. roll a die num_rolls times for i in range(num_rolls): die = random.randint(1, 6) # 2. try to count using the dictionary # rolls[key] = value # test to see if this key exists # is the value in the die variable # already a key in rolls. Suppose you rolled a 6... # 6 in the keys of {} -> False # 6 in the keys of {6: 1} -> True if die in rolls: # rolls[die] = rolls[die] + 1 rolls[die] += 1 else: rolls[die] = 1 return rolls def main(): print("Lecture 15 - dicts") rolls = count_rolls(5) print(rolls) # experiments! # can we use lists as values? yes! # (you can also use dicts) print({2: ["Emma", "Rohan"], 4: ["Sam", "Jordan"]}) # lists as keys? -> NO # TypeError: unhashable type: 'list' # lists can change, what happens if they change when they # are already keys??!?! # print({["Emma", "Rohan"]: 2, ["Sam", "Jordan"]: 4}) # can we use boolean values as keys? Yes! # you can't ever have more than 2 k-v pairs print({True: 78, False: 45}) # as values? Yes! print({"Jane": False, "Amisha": True, "Aditya": False}) # stuff from lecture 14 names_to_animals = {"Prof. Felix": "Blue Whale", "Prof. Laney": "Moose"} print(names_to_animals) print(names_to_animals["Prof. Felix"]) # reset the value with this key names_to_animals["Prof. Felix"] = "Turtle" print(names_to_animals) # add a new key names_to_animals["Jane"] = "Elephant" print(names_to_animals) print() # number of pairs in a dictionary print(len(names_to_animals)) print() # make an empty dictionary sections_to_foods = {} sections_to_foods[2] = "pasta" # our favorite # 1. sushi - # 2. pizza - # 3. steak sections_to_foods[4] = "sushi" print(sections_to_foods) print(len(sections_to_foods)) print() # access a key that doesn't exist # KeyError (equivalent of an IndexError with lists) # print(sections_to_foods[1]) pretty_print_dict(names_to_animals) pretty_print_dict(sections_to_foods) main()