Concept explainers
Below is the code to modify for the excerise. Use python
using the pickle module’s dump function to serialize the dictionary into a file and its load function to deserialize the object. Pickle is a binary format, so this exercise requires binary files.
”Reimplement your solutions to Exercises 9.6. Use the file-open mode 'wb' to open the binary file for writing and 'rb' to open the binary file for reading. Function dump receives as arguments an object to serialize and a file object in which to write the serialized object. Function load receives the file object containing the serialized data and returns the original object. The Python documentation suggests the pickle file extension .p.
Excercise 9.6 code
import json
def main():
n = int(input("Enter the number of students: "))
data = []
for i in range(n):
first = input("\nEnter First Name of Student " + str(i + 1) + ": ")
last = input("Enter Last Name of Student " + str(i + 1) + ": ")
te1 = int(input("Enter Te_st 1 Grade of Student " + str(i + 1) + ": "))
te2 = int(input("Enter Te_st 2 Grade of Student " + str(i + 1) + ": "))
te3 = int(input("Enter Te_st 3 Grade of Student " + str(i + 1) + ": "))
info = {}
info['first_name'] = first
info['last_name'] = last
info['ex_am1'] = te1
info['ex_am2'] = te2
info['ex_am3'] = te3
data.append(info)
gradebook_dict = {'students': data}
with open("grades.json", 'w') as _file:
json.dump(gradebook_dict, _file, indent=4)
print("\nWriting Done.\n")
with open("grades.json", 'r') as _file:
data = (json.load(_file))['students']
print(f'{"First Name":>15} {"Last Name":>15} {"test 1":>6} {"test 2":>6} {"test 3":>6} {"average":>7}')
totalTest1 = 0
totalTest2 = 0
totalTest3 = 0
count = 0
for i in data:
t1 = i['ex_am1']
t2 = i['ex_am2']
t3 = i['ex_am3']
totalTest1 += t1
totalTest2 += t2
totalTest3 += t3
count += 1
fname = i['first_name']
lname = i['last_name']
avg = (t1 + t2 + t3) / 3
print(f"{fname:>15} {lname:>15} {t1:>6d} {t2:>6d} {t3:>6d} {avg:>7.2f}")
print("-" * 60)
print(f"{'Test average':<32} {totalTest1 / count:>6.2f} {totalTest2 / count:>6.2f} {totalTest3 / count:>6.2f}")
main()
Trending nowThis is a popular solution!
Step by stepSolved in 2 steps
- help on this python problem, make alternative and beginner's codearrow_forwardWhat is wrong with the following code snippet that is supposed to print the contents of the file twice? infile = open ("input.txt", "r") for sentence in infile : print (sentence) for sentence in infile : print (sentence) Select one: O' Arun-time error occurs because the file does not exist O Nothing, the code prints the contents two times O Python cannot iterate over the file twice without closing and reopening the file The program cannot use the variable sentence twicearrow_forwardModify below program to read dictionary items from a file and write the inverted dictionary to another file. Include the following: The input file for your original dictionary (with at least six items). The Python program to read from a file, invert the dictionary, and write to a different file. The output file for your inverted dictionary. Program:" # Constructing the dictionary with different types of keys and lists of valueshobbies_dict = {"Sports": ["Soccer", "Basketball", "Swimming"],"Music": ["Guitar", "Piano", "Singing"],12345: ["Reading", "Writing", "Drawing"]}# Printing the original dictionaryprint("Original Dictionary:")print(hobbies_dict)# Function to invert the dictionarydef invert_dict(d):inverse = dict()for key in d:values_list = d[key]for value in values_list:if value not in inverse:inverse[value] = [key]else:inverse[value].append(key)return inverse# Running the modified invert_dict function on the dictionaryinverted_dict = invert_dict(hobbies_dict)# Printing the…arrow_forward
- I need someone to fix my Python code given the prompy. I can't get it to save the codon counts as a file. Write Code that completes the following 2 objectives 1. Build a function that takes a record from your FASTA file as an argument, and returns a count of each amino acid coded for by the codons of the sequence. Keep in mind that because these records are not necessarily in the proper reading frame, so the user should be prompted to select a reading frame (0, +1, +2). 2. In this section, you will be reading in this file of apple genes and, based on these coding sequences, generate a codon usage bias table for this species. aa_dict = {'Met':['ATG'], 'Phe':['TTT', 'TTC'], 'Leu':['TTA', 'TTG', 'CTT', 'CTC', 'CTA', 'CTG'], 'Cys':['TGT', 'TGC'], 'Tyr':['TAC', 'TAT'], 'Trp':['TGG'], 'Pro':['CCT', 'CCC', 'CCA', 'CCG'], 'His':['CAT', 'CAC'], 'Gln':['CAA', 'CAG'], 'Arg':['CGT', 'CGC', 'CGA', 'CGG', 'AGA', 'AGG'], 'Ile':['ATT', 'ATC', 'ATA'], 'Thr':['ACT', 'ACC', 'ACA', 'ACG'],…arrow_forwardQ. Write a program that add a new column to ‘B1.csv’ file named as Sequence then read multiple sequences from the user and add the data in every row of ‘B1.csv’ file. Programming language python Don't use pointers or arrays Paste the screenshots of full program with outputarrow_forwardCan you give the answer to these two questionsarrow_forward
- Python Help... Write a function stats() that takes one input argument: the name of a text file. The function should print, on the screen, the number of lines (line count), words(word count), and characters(character count) in the file; your function should open the file only once. Hints:Use the print format() module to print results and remember to save the function and the text file in the same directory. def stats(filename): ' Put in docstring’ # get file content infile = _____________________ # ______________ content = ___________________ # ______________ infile ______________# ______________ # replace punctuation with blank spaces and obtain list of words table = ________________________ # _______________ words = _______________________ # _______________ print___________________________# _______________ print___________________________# _______________ print__________________________# _______________ How it should run Result of running the function. >>>…arrow_forwardPython - Text Processing Write a function copy(x, y) that can copy a file x into another file y. Use demo.txt as the input to verify your function. _Hint_: use functions open( ), read( ), write( ), and close( ).arrow_forwardExercise 1) Creating and manipulating Data frames Problem Description a) Create a new code cell or a new python file. b) Write a python code that generates a data dictionary, Exams, as follows: All Exams are represented as a dictionary. 港 "Exam1", "Exam2", and "Exam3" are keys and theirs grades are values of the keys. c) Write a python code that generates a data frame, Grade Sheet, from Exams in b. d) Customize Grade Sheet indices with attributes "Student1", "Student2", "Student3", and "Student4". Then, print Grade Sheet which should be as follows: Exam1 Exam2 Exam 3 Student 1 3.5 4.5 2.5 Student 2 1.5 2 4.2 Student 3 1.5 1.4 3.5 2.5 Student e) Add a new column Total to the data frame, Grade Sheet, Total represents a sum of all exams for each student f) Print a summary statistics for each column including: maximum, minimum, and average. g) Sort Grade Sheet based on Total column in ascending order and then print Grade Sheetarrow_forward
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education