CS1101-Unit08 programming assignment

.docx

School

University of the People *

*We aren’t endorsed by this school

Course

1101

Subject

Computer Science

Date

Jan 9, 2024

Type

docx

Pages

3

Uploaded by BaronEmuPerson965

The input file I will be working with is called “fruits.txt” and contains the following text: { 'apple': 'red', 'banana': 'yellow', 'cherry': 'red', 'mango': 'yellow', 'grapes': 'purple', 'plum': 'purple', 'lime': 'green', 'lemon': 'yellow' } The Python program I have written is as follows: Running the open() function along with the with statement means it will close my file automatically once the program is finished with it (Chris, 2022.) Writing it this way means I do not need to remember to write any close() instructions, and my program code will be more concise.
Next, the file is read into a string assigned to the variable contents . It is evaluated by Python using the eval() function and recognized as a dictionary due to the curly brackets ( {} ) at the beginning and end of the text content. I began with the inverted dictionary function presented by the text (Downey, 2015, sec. 11.5 Dictionaries and lists) and then modified it to suit this assignment’s requirements. Inverse = {} creates a new empty dictionary called “inverse.” Next, a for loop iterates over the original dictionary, assigning each key-value pair to the key and value variables. If a value is not already contained within the inverse dictionary, it is added as a new item. That means that otherwise it is already present, in which case the key is appended to the list. The program concludes by opening a new file called “inverse_fruits.txt” in write mode (which automatically creates the file if it does not already exist) to contain the new, inverted dictionary. File.write(str(inverse)) writes our new inverse dictionary to the file, ensuring that it is formatted as a string in the process. Finally, a confirmation message is printed in the interpreter if everything goes as planned. When the program is run, the interpreter provides the following output: The new file that was created, “fruits_inverse.txt,” contains the following text: {'red': ['apple', 'cherry'], 'yellow': ['banana', 'mango', 'lemon'], 'purple': ['grapes', 'plum'], 'green': ['lime']}
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help