Without having any additional information, the following modifications will improve code style and should also improve performance (depending on size of data). On my machine, this approach provides a ~5x speed-up for a dictionary with 1 million random values and a ~15x speed-up for 5 million random values.
def value_to_str(value):
return "" if value is None else str(value)
csv_data = "|".join(map(value_to_str, order_dic_keys.values()))
with open("parse_data.csv", "w") as f:
f.write(csv_data)
Instead of manually stepping through the dictionary with a for-loop, using higher-order functions we take a functional approach to creating the csv-string. This should allow the interpreter to better optimize our code.
Notes:
- Manual / Incremental string construction (
string = string + string
/ string += string
) is rather slow, try to avoid it when possible
empty += "" + "|"
, the empty string does nothing here --> empty += "|"
- You don't need to and shouldn't create
empty
inside the open file context manager. The open file context manager should only contain code that absolutely has to be there
empty
is only empty at initialization, it won't be empty at any other point during your program. It should not be named empty
.
- You don't need to copy the write-string
empty[:]
when writing it to the file, simply omit the [:]
- As we're only using the dictionary values (not the keys), we can simply use
dict.values
instead of dict.items
order_dic_keys
look like, an ordinary dictionary? How big are we talking and will there be any nesting? If so, how far down? \$\endgroup\$DictWriter
from modulecsv
? Re-inventing the wheel? Tag! \$\endgroup\$None
into an empty string (as well as a bunch of other annoying details). You can see more details in my answer. \$\endgroup\$