Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

A psychology student is carrying out an experiment in which she repeatedly asks

ID: 3757216 • Letter: A

Question

A psychology student is carrying out an experiment in which she repeatedly asks people to "think of an object, any object". She wants to see what objects people think of under this situation. She enters each guessed object into a text file, one object per line Help her to analyse the data by writing a function create_dictionary(filename) that reads the named file and returns a dictionary mapping from object names to occurrence counts (the number of times the particular object was guessed). For example, given a file mydata.txt containing the following dog triceratops persian cat dog persian cat large white fluffy thing persian cat the function would return the dictionary 'dog: 2, 'triceratops':'persian cat': 3, 'large white fluffy thing': 1 Notes: .You may assume the given file exists, but it may be empty (i.e., containing no lines) . Keys must be inserted into the dictionary in the order in which they appear in the input file . In some of the tests we display the keys in insertion order; in others were sort the keys alphabetically Leading and trailing white space should be stripped from object names Empty object names (e.g. blank lines or lines with only whitespace) should be ignored Some test files can be downloaded here, unzip them into your program folder For example: Test Result # Testing with the example data in the question dog: 2 dictionary -create_dictionary('data.txt') for key in dictionary: triceratops: 1 persian cat: 3 print(key +'str(dictionary[key])) large white fluffy thing: 1

Explanation / Answer

def create_dictionary(filename): d = {} with open(filename, 'r') as f: for line in f: words = line.strip().split() for word in words: word = word.strip() if len(word) > 0: if word not in d: d[word] = 0 d[word] += 1 return d print(create_dictionary('input.txt'))

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote