需要有关词典,csv文件和列表的帮助

时间:2016-11-21 18:23:27

标签: python list dictionary

好吧,所以我需要一个代码,它将获取一个csv文件并读取其中的值(到目前为止,我已经将该部分缩小了)。

我遇到的问题是创建一个包含这些值的列表,并按照重复次数减少到最重新发生的顺序排序。也没有重复的值。

以下是我所拥有的:

import csv
B = []
K = []
def readandprocess(name):
with open(name, newline='') as csvf:
    freader = csv.reader(csvf,delimiter=',',quotechar='"')
    datasg = {}
    artists = []



    for row in freader:
        artist = row[2]
        B.append(artist)


    for artist in B:
            c = B.count(artist)
            K.append(artist + str(c))


    list(set(K))
    print(K)

    #for row in freader:
        #artist = row[2]
        ###song = row[1]
        #if artist == 'Rolling Stones':
        #    print('Rolling Stones title: ',row[1])
        #if artist not in datasg:
        #   datasg[artist] = [song]
       #else:
            #datasg[artist].append(song)
    #for artist in datasg:
        #print(artist, datasg[artist])
    print( '--------------------------------------')
    info = datasg.items()
   # tosort = [(len(t[1]),t[0]) for t in info]
   # info = sorted(tosort)
   # print(info[-30:])
   # print(info)

print(len(datasg))   # currently 0, populate at will #Number of keys in dictionary
return datasg


if __name__ == '__main__':
    datasg = readandprocess('data/top1000.csv')

1 个答案:

答案 0 :(得分:0)

尝试使用Counter。在列表中包含所需的所有项目后,您可以使用计数器,然后拨打most_common(n)以获取n最常见的元素。