简体   繁体   中英

Using OrderedDict to output list in reverse order from CSV file

I need to have a import a CSV file containing:

name,mean performance,std dev
Alice,100,0
Bob,100,5 
Clare,100,10
Dennis,90,0
Eva,90,5

and have the output come out sorted as:

{'Dennis': (90.0, 0.0), 'Clare': (100.0, 10.0), 'Eva': (90, 5.0), 'Bob': (100.0, 5.0), 'Alice': (100.0, 0.0)}

So far I have:

import csv
import collections

def sailorPerf(filename, header=True):

    with open(filename, mode='r') as csvfile:
        r = csv.reader(csvfile)
        if header==True:
            next(r)
        od = collections.OrderedDict((row[0], row[1]) for row in r)
    print (od)

Which outputs:

OrderedDict([('Alice', ' 100'), ('Bob', ' 100'), ('Clare', ' 100'), ('Dennis', ' 90'), ('Eva', ' 90')])

I was wondering how to add the third column into the result as well as change the formatting to have the ordereddict part removed from the output and change around how the output is given to have the name and output as it is in the intended result.

(row[0], row[1])更改为(row[0], tuple(row[1:]))以将第二个作为包含来自索引1的所有元素的列表-列表结尾,然后将其强制转换为元组。

You need to sort the data, by the second and third columns casting to int:

from collections import OrderedDict
def sailorPerf(filename, header=True):
    with open(filename, mode='r') as csvfile:
        r = csv.reader(csvfile)
        if header:
            next(r)
        od = OrderedDict((name, tuple(rest)) 
                  for name,*rest in sorted(r, key=lambda x: (int(x[1]), int(x[2]))))
        return od


print(sailorPerf("test.txt"))

Output:

OrderedDict([('Dennis', ('90', '0')), ('Eva', ('90', '5')),
        ('Alice', ('100', '0')), ('Bob', ('100', '5')),
        ('Clare', ('100', '10'))])

If you really don't want to see the OrderedDict you can could call list(od.items) :

print(list(sailorPerf("test.txt").items()))

OrderedDict([('Dennis', ('90', '0')), ('Eva', ('90', '5')), 
          ('Alice', ('100', '0')), ('Bob', ('100', '5')),
                 ('Clare', ('100', '10'))])

For python2 just unpack:

def sailorPerf(filename, header=True):
    with open(filename, mode='r') as csvfile:
        r = csv.reader(csvfile)
        if header==True:
            next(r)
        od = OrderedDict((nm, (mn, std))) 
                  for nm, mn, std in sorted(r,key=lambda x: (int(x[1]),int(x[2]))))
        return od

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM