In: Computer Science
Language: Python
Function name : sort_by_rating
Parameters : file (.csv file), category (string), order
(boolean)
Returns: None
Description : You want to see what order the items of a particular
category in your file would be in if you sorted them by rating.
Given a file, a category of clothing, and an order boolean (True
for ascending order, False for descending order), create a function
that writes a file called “sorted_items.csv” that includes all of
the items in the specified category in sorted order by
ranking.
The format of the file should look like this:
item name |
rating |
item name 1 |
rating 1 |
item name 2 |
rating 2 |
... |
... |
(NOTE: there will be a header row at the top of each .csv file)
Note: If your input file contains no items in the specified
category, your “sorted_items.csv” file should still be created and
have the header row. Also, your written files should end in a new
line character
Hint : You can use the built-in Python .sort() method on a list of
tuples. The tuples will get sorted by the first item in each tuple.
Example:
>>> list_of_tups = [(5, "cats"), (6, "kittens"), (1,
"lizards")] >>> list_of_tups.sort()
>>> print(list_of_tups)
[(1, 'lizards'), (5, 'cats'), (6, 'kittens')]
Test cases:
>>> sort_by_rating("uniqlo.csv","tops",True)
The python 3 code for your assignment is as: Use proper indentation as shown in screenshot.
*******************************writeCsv.py****************************************
import csv
def sort_by_ranking(fname,category,x):
data=[]
x=not x
with open(fname) as f:
reader = csv.DictReader(f, delimiter=',')
for row in reader:
name = row['item name']
rating = row['rating']
cat=row['category']
if category==cat:
data.append((name,rating))
data.sort(key=lambda x:x[1],reverse=x)
data.insert(0, ('item name','rating'))
with open('sorted_items.csv', 'w') as f:
writer = csv.writer(f , lineterminator='\n')
for item in data:
writer.writerow(item)
sort_by_ranking('uniqlo.csv','tops', True)