python - Add key/values to dictionary using condition -


i have list of items i'm adding dictionary below:

cols = ['cust', 'model', 'sn', 'date', 'charge', 'qty', 'total'] open('userfeeinvoicing.csv', 'r') infile:     ranpak_dict = {         row[2]: dict(zip(cols, row)) row in csv.reader(infile)     } 

is there anyway add records have charge =/= 0 or charge > 0

rather use csv.reader(), use csv.dictreader() object. object makes lot easier both create dictionaries , filter rows; code, refactored use dictreader(), looks this:

cols = ['cust', 'model', 'sn', 'date', 'charge', 'qty', 'total'] open('userfeeinvoicing.csv', 'r') infile:     reader = csv.dictreader(infile, fieldnames=cols)     ranpak_dict = {row['sn']: row row in reader} 

the csv.dictreader() object exactly dict(zip(cols, row)) call does; build dictionary each row, given sequence of fieldnames.

filtering in list, dict or set comprehension works adding additional loops; add if <condition> loop:

ranpak_dict = {row['sn']: row row in reader if int(row['charge']) > 0} 

note int() call; assuming charge column always contains digits.

if textual fields quoted, set quoting=csv.quote_nonnumeric, @ point columns without quotes automatically converted float you. that'd reduce code to:

reader = csv.dictreader(infile, fieldnames=cols, quoting=csv.quote_nonnumeric) ranpak_dict = {row['sn']: row row in reader if row['charge'] > 0} 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -