python将csv文件作为字典读取并对计数器进行排序和递增

时间:2014-09-23 15:52:41

标签: python csv dictionary

我希望有人指出我正确的方向。从我所读过的内容来看,我相信使用字典最适合这种需要,但我绝不是一个主程序员,我希望有人可以解决问题,并帮助我。这是我的CSV文件:

11362672,091914,100914,100.00,ITEM,11,N,U08
12093169,092214,101514,25.00,ITEM,11,N,U10
12162432,091214,101214,175.00,ITEM,11,N,U07
11362672,091914,100914,65.00,ITEM,11,N,U08
11362672,091914,100914,230.00,ITEM,11,N,U08

我想将第一列视为一个键,并将以下列作为该键的值以便:

  1. 按键
  2. 对数据进行排序
  3. 反击事件
  4. 附加计数器
  5. 这是我想要达到的输出:

    1,11362672,091914,100914,100.00,ITEM,11,N,U08 # occurrence 1 for key: 11362672
    2,11362672,091914,100914,65.00,ITEM,11,N,U08 # occurrence 2 for key: 11362672
    3,11362672,091914,100914,230.00,ITEM,11,N,U08 # occurrence 3 for key: 11362672
    1,12093169,092214,101514,25.00,ITEM,11,N,U10 # occurrence 1 for key: 12093169
    1,12162432,091214,101214,175.00,ITEM,11,N,U07 # occurrence 1 for key: 12162432
    

    我需要保持每一行的完整性,这就是为什么我认为字典效果最好的原因。我没有多少,但这就是我的开始。这是我需要帮助来排序,计数和附加计数器的地方。

    import csv
    with open('C:/Download/item_report1.csv', 'rb') as infile:
         reader = csv.reader(infile)
         dict1 = {row[0]:row[1:7] for row in reader}
         print dict1
    

    给了我:

    {
    '11362672': ['091914', '100914', '230.00', 'ITEM', '11', 'N'], 
    '12093169': ['092214', '101514', '25.00', 'ITEM', '11', 'N'], 
    '12162432': ['091214', '101214', '175.00', 'ITEM', '11', 'N']
    }
    

1 个答案:

答案 0 :(得分:1)

简而言之,您应该使用计数器来计算密钥和列表来存储行。

当您在csv中阅读时,记录您看到键值的次数,并在阅读时将其插入每行的开头。

在您阅读完文件后,您可以先按键值和出现计数器秒进行排序。

import csv

counter = {}
data = []

with open('report.csv','rb') as infile:
  for row in csv.reader(infile):
    key = row[0]
    if key not in counter:
      counter[key] = 1
    else:
      counter[key] += 1
    row.insert(0,counter[key])
    data.append(row)

for row in sorted(data,key=lambda x: (x[1],x[0])):
  print row

这是同样的事情,根据官方风格指南略有不同,有4个空格,而不是我个人喜欢的两个。

import csv

# key function for sorting later
def second_and_first(x):
    return (x[1],x[0])

# dictionary to store key_fields and their counts
counter = {}
# list to store rows from the csv file
data = []

with open('report.csv','rb') as infile:
    for row in csv.reader(infile):
        # For convenience, assign the value of row[0] to key_field
        key_field = row[0]
        # if key_field is not in the dictionary counter. Add it with a value of 1
        if key_field not in counter:
            counter[key_field] = 1
        # otherwise, it is there, increment the value by one.
        else:
            counter[key_field] += 1
        # insert the value associated with key_field in the counter into the start of
        # the row
        row.insert(0,counter[key_field])
        # Append the row to 
        data.append(row)

for row in sorted(data,key=second_and_first):
    print row