Question

PYTHON Hello can someone create the following functions? I'm not sure how to start on them....

PYTHON Hello can someone create the following functions? I'm not sure how to start on them.

makeDictionary

Define a function named makeDictionary with two parameters. The first argument passed the function must be a list of strings to be used as keys, while the second is a list of the same length containing values (of some type).

This function must return a dictionary consisting of the keys paired with the corresponding values.

For example, makeDictionary(['apno','value'],['REP-12','450']) must return this dictionary: {'apno': 'REP-12', 'value': '450'}

readDataFromCSVFile

N.B. When opening a file for reading you will need to add an extra keyword parameter to the open(...) function call in order for AutoLab to properly handle all the characters in the CSV files: encoding="utf-8". The function call should be:

open(filename, newline='', encoding="utf-8")

Define a function named readDataFromCSVFile with one parameter. The argument passed to the function should be a string which is the name of a CSV file containing data. The file will have a header row and data rows. For example, suppose the file sample.csv contains:

apno,value

REP-12,450

ELEC-72,2000

The file has a header row:

apno,value

After the header row the file has two data rows:

REP-12,450

ELEC-72,2000

This function must return a list of dictionaries. Each dictionary must pair a key from the header row with the corresponding value from given data row. For example, readDataFromCSVFile("sample.csv") must return the following dictionary: [{'apno': 'REP-12', 'value': '450'},{'apno': 'ELEC-72', 'value': '2000'}]

dictionaryToListOfValues

Define a function named dictionaryToListOfValues with two parameters. The first argument of this function will be a list of keys, while the second is a dictionary. This function must return the values associated with each of the keys in the dictionary, in the same order that the keys are given in the first argument. You may assume that each key in the first argument exists as a key in the dictionary.

For example, if d = {'apno': 'ELEC-72', 'value': '2000'} then

dictionaryToListOfValues(['apno','value'],d)

must return

['ELEC-72', '2000']

while

dictionaryToListOfValues(['value','apno'],d)

must return

['2000','ELEC-72']

writeDataToCSVFile

Define a function named writeDataToCSVFile with four parameters. The first argument is a string, the name of the file which data will be written to. The second argument is a list of dictionaries, like the one readDataFromCSVFile produces. The third is a list of keys. You may assume that each key in the third argument exists as a key in each of the dictionaries in the second argument. The fourth is a Boolean value.

This function must write the values from each dictionary as a record to a CSV file. The order of the values in the record must correspond to the order of the keys in the third argument. If the fourth argument is True a header row is written as the first record of the CSV file, followed by the data rows; otherwise only the data rows are written.

For example, if data = [{'apno': 'REP-12', 'value': '450'}, {'apno': 'ELEC-72', 'value': '2000'}] then the call

writeDataToCSVFile("sample_header.csv",data,['value','apno'],True)

must write to the file named sample_header.csv the following contents:

value,apno

450,REP-12

2000,ELEC-72

while the call

writeDataToCSVFile("sample.csv",data,['apno','value'],False)

must write to the file named sample.csv the following contents:

REP-12,450

ELEC-72,2000

0 0
Add a comment Improve this question Transcribed image text
Answer #1

****This requires some effort so please drop a like if you are satisfied with the solution****

I have satisfied all the requirements of the question and I'm providing the screenshots of output obtained and files and code for your reference...

Code:

import csv
import os


def makeDictionary(keys, values):
    dict = {}
    for i in range(0, len(keys)):
        dict[keys[i]] = values[i]
    return dict


keys = ['apno', 'value']
values = ['REP-12', '450']
print("Function 1 ", makeDictionary(keys, values))


def readDataFromCSV(name):
    result = []
    filename = os.path.join("C://Users/THE__INFINITY/Desktop", name)
    reader = csv.DictReader(open(filename, newline='', encoding="utf-8"))
    for raw in reader:
        data = {}
        for key in raw.keys():
            data[key] = raw[key]
        result.append(data)
    return result


print("Function 2 ", readDataFromCSV("sample1.csv"))


def dictionaryToListOfValues(keys, dict):
    values = []
    for key in keys:
        values.append(dict[key])
    return values


keys2 = ['apno', 'value']
dict = {'apno': 'ELEC-72', 'value': '2000'}
print("Function 3 ", dictionaryToListOfValues(keys2, dict))
keys2 = ['value', 'apno']
print("Function 3 ", dictionaryToListOfValues(keys2, dict))


def writeDataToCSVFile(name, dicts, keys, header):
    filename = os.path.join("C://Users/THE__INFINITY/Desktop", name)
    if header:
        with open(filename, 'wt', newline='') as file:
            writer = csv.writer(file, delimiter=',')
            writer.writerow(i for i in keys)
            for j in dicts:
                values = []
                for key in keys:
                    values.append(j[key])
                writer.writerow(values)
    else:
        with open(filename, 'wt', newline='') as file:
            writer = csv.writer(file, delimiter=',')
            for j in dicts:
                values = []
                for key in keys:
                    values.append(j[key])
                writer.writerow(values)


# function 4 to write data to a csv file
writeDataToCSVFile("sample2.csv", readDataFromCSV("sample1.csv"), keys2, True)
writeDataToCSVFile("sample3.csv", readDataFromCSV("sample1.csv"), keys, False)

Sample1.csv (input file used for 2nd function):

Output Screenshots:

Function 4 output is a file one with header and one with no header...

Code Screenshots:

Add a comment
Know the answer?
Add Answer to:
PYTHON Hello can someone create the following functions? I'm not sure how to start on them....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Define a Python function named borough_count that has one parameter. The parameter is a string representing...

    Define a Python function named borough_count that has one parameter. The parameter is a string representing the name of a CSV file. The CSV file is a subset of NYC's dataset of all film permits issued since April 2016. Each row in the CSV file has the format: Event Id, Police Precinct(s), Event Type, Borough, Category Your function must return a dictionary. The keys of this dictionary will be the boroughs read in from the file (boroughs are at index...

  • PYTHON PROGRAM by using functions & dictionary or set. - must create a variable to hold...

    PYTHON PROGRAM by using functions & dictionary or set. - must create a variable to hold a dictionary or sets - must define a function that accepts dictionaries or sets as an argument A dictionary maps a set of objects (keys) to another set of objects (values). A Python dictionary is a mapping of unique keys to values. For e.g.: a dictionary defined as: released = { "iphone" : 2007, "iphone 3G": 2008, "iphone 3GS": 2009, "iphone 4" : 2010,...

  • You will need to define 2 Python functions. These functions could be used by a website...

    You will need to define 2 Python functions. These functions could be used by a website tracking movie data. Each movie is represented as a dictionary containing three keys:/p> the key "film" whose value is a string representing the name of the film; the key "tomat" whose value is am int of its rating from a well-known website; the key "gross" whose value is a float equalling its worldwide gross income (in million of dollars). First, define a key selector...

  • This script will create a dictionary whose keys are all the directories listed in thePATH system...

    This script will create a dictionary whose keys are all the directories listed in thePATH system variable, and whose values are the number of files in each of these directories. The script will also print each directory entry sorted by directory name. The script will use the following five functions to get the required results get_environment_variable_value() get_dirs_from_path() get_file_count() get_file_count_for_dir_list() print_sorted_dictionary() get_environment_variable_value() The header for this function must be This function must accept a shell variable as its only parameter The...

  • Help needed with Python 3: Dictionaries and Sets. The problem is one that asks the user to create...

    Help needed with Python 3: Dictionaries and Sets. The problem is one that asks the user to create a completed program that prompts the user for the name of a data file, and reads the contents of that data file, then creates variables in a form suitable for computing the answer to some questions. The format should be in the same manner as the attached .py file. All subsequent assignment details (.py and .csv files) can be found at this...

  • Define the functions in Python 3.8 1. Write a function most frequent n that takes a...

    Define the functions in Python 3.8 1. Write a function most frequent n that takes a list of strings and an integer n, and that returns a dictionary where the keys are the top n most frequent unique words in the list, and the values are the frequency of each word: For example, most frequent n(text, 3) should return the dictionary {'is': 2, "the’: 3, 'of': 2}, and most frequent n(text, 2) could return either {'is': 2, 'the’: 3} or...

  • please do a and b Lab Exercise 9 Assignment Overview This lab exercise provides practice with...

    please do a and b Lab Exercise 9 Assignment Overview This lab exercise provides practice with dictionaries of lists and sets in Python. A. Write a program using Dictionaries of lists Consider the file named "lab9a.ру" Given two files named exactly continents. txt and cities.txt (no error checking of the file name is needed) of continents, countries and cities. Write a program to read continents, countries and their cities, put them in a nested dictionary and print them (no duplicates...

  • Questions 1. How to create a comment in python? 2. The way to obtain user input...

    Questions 1. How to create a comment in python? 2. The way to obtain user input from command line 3. List standard mathematical operators in python and explain them 4. List comparison operators in python 5. Explain while loop. Give example 6. Explain for loop. Give example 7. How to create infinite loop? And how to stop it? 8. Explain a built-in function ‘range’ for ‘for’ loop 9. Explain break statement 10. Explain continue statement 11. Explain pass statement 12....

  • Hey guys I need help with this assignment. However it contains 7 sub-problems to solve but I figured only 4 of them can...

    Hey guys I need help with this assignment. However it contains 7 sub-problems to solve but I figured only 4 of them can be solved in one post so I posted the other on another question so please check them out as well :) Here is the questions in this assignment: Note: Two helper functions Some of the testing codes for the functions in this assignment makes use of the print_dict in_key_order (a dict) function which prints dictionary keyvalue pairs...

  • The way I understand it is i'm trying to link a list that I read into...

    The way I understand it is i'm trying to link a list that I read into python from a cvs file to json and xml and pass the doctest. Please refere the lines where I show what I did below. home / study / engineering / computer science / questions and answers / """this script converts a csv file with headers ... Question: """This script converts a CSV file with headers to... Bookmark """This script converts a CSV file with...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT