我有一个项目列表,我正在添加到下面的字典中:
COLS = ['CUST', 'MODEL', 'SN', 'DATE', 'CHARGE', 'QTY', 'TOTAL']
with open('UserfeeInvoicing.csv', 'r') as infile:
ranpak_dict = {
row[2]: dict(zip(COLS, row)) for row in csv.reader(infile)
}
无论如何只能添加包含CHARGE =/= 0
或CHARGE > 0
答案 0 :(得分:3)
使用csv.DictReader()
object而不是csv.reader()
。该对象使得创建字典和过滤行变得容易得多;您重构为使用DictReader()
的代码如下所示:
COLS = ['CUST', 'MODEL', 'SN', 'DATE', 'CHARGE', 'QTY', 'TOTAL']
with open('UserfeeInvoicing.csv', 'r') as infile:
reader = csv.DictReader(infile, fieldnames=COLS)
ranpak_dict = {row['SN']: row for row in reader}
csv.DictReader()
对象完全您dict(zip(COLS, row))
调用的内容;在给定一系列字段名的情况下,从每一行构建一个字典。
在列表,dict或set comprehension中过滤就像添加其他循环一样;只需将if <condition>
添加到循环中:
ranpak_dict = {row['SN']: row for row in reader if int(row['CHARGE']) > 0}
注意int()
电话;我假设CHARGE
列总是包含数字。
如果您的文字字段全部被引用,您也可以设置quoting=csv.QUOTE_NONNUMERIC
,此时所有没有引号的列都会自动转换为float
。这会将代码缩减为:
reader = csv.DictReader(infile, fieldnames=COLS, quoting=csv.QUOTE_NONNUMERIC)
ranpak_dict = {row['SN']: row for row in reader if row['CHARGE'] > 0}
答案 1 :(得分:1)
您可以执行以下操作:
ranpak_dict = {}
COLS = ['CUST', 'MODEL', 'SN', 'DATE', 'CHARGE', 'QTY', 'TOTAL']
with open('UserfeeInvoicing.csv', 'r') as infile:
reader = csv.reader(infile)
for row in reader:
if float(row[COLS.index('CHARGE')]) >= 0:
ranpak_dict[row[2]] = dict(zip(COLS, row))