I have a dict of Boolean flags in my app. As I work through a data set, I key into the dict using fields from the data and flag whether I've already performed a do-once operation on them. Right now, I'm initializing a dict of False values with the right keys, then copying that dict at the start of the loop that operates on the data. Here's a code snippet from a function that distributes database records to a set of .csv files:
do_once_defaults = dict.fromkeys([f for f in output_file_names], False)
for db in db_files:
do_once = dict(do_once_defaults)
for row in cur.execute(query, params):
if not do_once[row[0]]:
do_once[row[0]] = True
_replace_csv_headers(output_files[row[0]], [r[0] for r in cur.description])
_write_record_to_csv(row[1:])
Is there a better way to reset the dict of flags on each outer iteration? A more Pythonic way?
You'd better not use a dict at all. A dict where values are just booleans is really just a set (unless you actually distinguish the three values True/False/notIncluded, but you're not doing that).
I think this is what you want:
for db in db_files:
done = set()
for row in cur.execute(query, params):
if row[0] not in done:
done.add(row[0])
_replace_csv_headers(output_files[row[0]], [r[0] for r in cur.description])
_write_record_to_csv(row[1:])
((Edit: This is about the now-fixed do_once = do_once_defaults) Btw, you're not copying the dict. Your do_once is just another reference to the same dict object that do_once_defaults references. So you're not resetting the flags there. The simplest way to actually make a copy would be do_once = dict(do_once_defaults), but I really think you should use the set as suggested above.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With