1 Given a variable electionresults that is associated with
1) Given a variable , election_results, that is associated with a dictionary that maps candidate names to votes received, associate the name of the candidate with the most votes with the variable winner.
2) Store four file objects corresponding to the files winter2003.txt , spring2003.txt, summer2003.txt, and fall2003.txt in the variables winter, spring, summer, and fall (respectively), and open them all for reading.
3) Write a statement to open the file yearsummary.txt in a way that erases any existing data in the file.
4) Given four files named asiasales2009.txt, europesales2009.txt, africasales2009.txt, and latinamericasales2009.txt, define four file objects namedasia, europe, africa, and latin, and use them, respectively, to open the four files for writing.
Python 3.5 (only simple coding and answers will do)
Solution
# !/usr/bin/env python3 # -*- coding: utf-8 -*- \"\"\" Created on Wed Feb 8 15:23:02 2017 @author: \"\"\" ######################## Answer1 ############################## # creating dictonary election_results = {\"candidate1\": 100, \"candidate2\": 200, \"candidate3\": 150, \"candidate4\": 500} # sorting the item in dictonary and reversing it and geting the winner winner = sorted(election_results.items(), key=lambda x: x[1], reverse=True)[0][0] ####################### End ################################### ######################## Answer2 ############################## # opening files for reading and closing it winter = open(\"winter2003.txt\", \'r\') spring = open(\"spring2003.txt\", \'r\') summer = open(\"summer2003.txt\", \'r\') fall = open(\"fall2003.txt\", \'r\') winter.close() spring.close() summer.close() fall.close() ####################### End ################################### ######################## Answer3 ############################## # here creating new file f = open(\'yearsummary.txt\', \'w\') f.close() ####################### End ################################### ######################## Answer4 ############################## # opening four file for writing asia = open(\'asiasales2009.txt\', \'w\') europe = open(\'europesales2009.txt\', \'w\') africa = open(\'europesales2009.txt\', \'w\') latin = open(\'latinamericasales2009.txt\', \'w\') asia.close() europe.close() africa.close() latin.close() ####################### End ###################################