0

I have a csv file a list of name and mean. For example:

ali,5.0
hamid,6.066666666666666
mandana,7.5
soheila,7.833333333333333
sara,9.75
sina,11.285714285714286
sarvin,11.375

I am going to rewrite the csv by three lower mean. I have write the code, but I have a problem to write the csv again. I should keep the mean number exactly as an input.

import csv
import itertools
from collections import OrderedDict
with open ('grades4.csv', 'r') as input_file:
    reader=csv.reader(input_file)
    val1=[]
    key=list()
    threelowval=[]
    for row in reader:
        k = row[0] 
        val=[num for num in row[1:]] #seperate a number in every row 
        key.append(k) #making a name -key- list
        val1.append(val) #making a value list
        value = list(itertools.chain.from_iterable(val1)) #making a simple list from list of list in value
        value=[float(i) for i in value] ##changing string to float in values
    #print(key)
    #print(value)
    dictionary = dict(zip(key, value))
    #print(dictionary)
    findic=OrderedDict(sorted(dictionary.items(), key=lambda t: t[1])) ##making a sorted list by OrderedDict
    #print(findic)
##make a separation for the final dict to derive the three lower mean
    lv=[]
    for item in findic.values():
            lv.append(item)
    #print(lv)
    for item in lv[0:3]:
            threelowval.append(item)
    print(threelowval)

I have tried below code but I get the error.

with open('grades4.csv', 'w', newline='') as output_file_name:
    writer = csv.writer(output_file_name)
    writer.writerows(threelowval)

expected result:

5.0
6.066666666666666
7.5
0

2 Answers 2

2

You should try this:

with open('grades4.csv', 'w', newline='') as output_file_name:
   writer = csv.writer(output_file_name)
   for i in threelowval:
       writer.writerow([i])
Sign up to request clarification or add additional context in comments.

Comments

0

I have tried below code and receive the correct results.

with open('grades4.csv', 'w', newline='') as output_file_name:
    writer = csv.writer(output_file_name)
    writer.writerows(map(lambda x: [x], threelowval))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.