将“if”条件添加到已排序的字典数据集中

时间:2016-05-13 01:14:26

标签: python for-loop dictionary sorteddictionary

我正在尝试使以下代码用于生成所需的输出。我怀疑我的错误是代码的格式,所以希望有人可以帮助我(编码仍然很绿)。这是我到目前为止编码的内容:

import csv

infile = open("source.csv", "rU")
incsv = csv.reader(infile, delimiter = ',')
outfile = open("sourceoutput.csv", "w")
outcsv = csv.writer(outfile, delimiter = ',')
dict = {}
header = incsv.next()

rowNum = 0
for row in incsv:
    data1, data2, name, data3, data4, data5, data6, data7, data8, data9, data10 = row
    lastname = name.split(", ")[0]
    firstname = name.split(", ")[1]

if data1 == "1":
    #Adding (lastname, firstname, data3, data4, data5) of data1 = 1  only into dictionary 'dict'
    if lastname not in dict:
        dict[lastname] = firstname, data3, data4, data5

#Printing data sorted by lastname in alphabetical order
names = dict.keys()
sorted_names = sorted(names)
for name in sorted_names:
    firstname, data3, data4, data5 = dict[lastname]
    outcsv.write("%s,%s,%s,%s,%s" % (lastname, firstname, data3, data4, data5))

infile.close()
outfile.close()

我怀疑在(lastname, firstname, data3, data4 and data5)时我定义了将dict添加到data1 == 1的if语句时出错。如何将此条件实现到for循环中并将相应的信息添加到字典中,以便按字母顺序重新排列?我的代码设置还需要其他什么吗?

提前致谢!

2 个答案:

答案 0 :(得分:0)

通过查看代码我可以理解,您需要为您的CSV的所有行添加数据到dict,因此您的if需要在for循环中,如下所示。 (仅供参考:您还可以将if个语句合并为一个,例如if data1 == "1" and lastname not in dict:

rowNum = 0
for row in incsv:
    data1, data2, name, data3, data4, data5, data6, data7, data8, data9, data10 = row
    lastname = name.split(", ")[0]
    firstname = name.split(", ")[1]

    if data1 == "1":
        #Adding (lastname, firstname, data3, data4, data5) of data1 = 1  only into dictionary 'dict'
        if lastname not in dict:
            dict[lastname] = firstname, data3, data4, data5

答案 1 :(得分:0)

尝试{_ 1},这是_csv.writer特定的。

doc:here

编辑:看看here