I have a list of items that I'm adding to dictionary below:
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)
}
Is there anyway to only add the records that have CHARGE =/= 0
or CHARGE > 0
Rather than use csv.reader()
, use csv.DictReader()
object . That object makes it a lot easier to both create your dictionaries and to filter the rows; your code, refactored to use DictReader()
, looks like this:
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}
The csv.DictReader()
object does exactly what your dict(zip(COLS, row))
call does; build a dictionary from each row, given a sequence of fieldnames.
Filtering in a list, dict or set comprehension works just like adding additional loops; just add if <condition>
to the loop:
ranpak_dict = {row['SN']: row for row in reader if int(row['CHARGE']) > 0}
Note the int()
call; I am assuming that the CHARGE
column always contains digits.
If your textual fields are all quoted, you could also set quoting=csv.QUOTE_NONNUMERIC
, at which point all columns without quotes are automatically converted to float
for you. That'd reduce the code to:
reader = csv.DictReader(infile, fieldnames=COLS, quoting=csv.QUOTE_NONNUMERIC)
ranpak_dict = {row['SN']: row for row in reader if row['CHARGE'] > 0}
You could do the following:
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))
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.