''' Author: Sohie Lee Purpose: CS111 Dictionaries practice using jeopardy json file (216930 questions) in the provided list of dicts. Date: Fall 2021 Filename: jeopardy.py ''' import json import random def getJeopardyList(jsonfile): ''' Returns the Jeopardy list of questions stored in the given json file ''' try: with open(jsonfile, 'r') as inputFile: jeopardyList = json.load(inputFile) return jeopardyList except FileNotFoundError: print('Oops, ran into a problem finding the file', jsonfile) except Exception: return 'Error attempting to read json file ' + jsonfile def makeCategoryDict(jList): '''Given the list of jeopardy dictionaries, creates a new category-based dictionary with categories as keys and lists of tuples with (question, answer) as values. ''' categoryDict = {} for question in jList: cat = question['category'] quest = question['question'] ans = question['answer'] if cat in categoryDict: categoryDict[cat].append((quest, ans)) else: categoryDict[cat] = [(quest, ans)] return categoryDict def playJeopardy(categoryDict, categoryList, numRounds): ''' Relies upon category dictionary to play the game for numRounds, using only specified categories in categoryList. ''' try: print("Welcome to Jeopardy! I will be your host today.") print('You can choose from these categories: ', categoryList) # initialize counter outside the for loop correct = 0 for round in range(numRounds): categoryChoice = input('Which category? ').upper() questionAnswerCombo = categoryDict[categoryChoice] theQuestion, theAnswer = random.choice(questionAnswerCombo) print(theQuestion) print() userAnswer = input('Please type your answer here: ') if userAnswer.lower().strip() == theAnswer.lower().strip(): print('Correct!') # count this as a correct answer correct += 1 else: print( 'Sorry, you were wrong, the correct answer is', theAnswer ) print('-' * 30) print( f"Your score: {correct} answer(s) correct out of {numRounds}" + f" ({correct/numRounds*100}%)" ) except KeyError: print('Sorry, that does not match one of my categories:', categoryList) # Testing code below here jeopardyList = getJeopardyList('jeopardy.json') jeopardyCategoryDict = makeCategoryDict(jeopardyList) playJeopardy( jeopardyCategoryDict, ['FASHION', 'ALMA MATERS', 'FACT OR FICTION?', 'THE OSCARS'], 5 )