3 ms·
Failing to use join is a big one. I have seen countless instances of people writing the logic to output commas in between items (like for CSV export) that they
by elandybarr 12y ago
Failing to use join is a big one.
I have seen countless instances of people writing the logic to output commas in between items (like for CSV export) that they want to concatenate into a string.
header_line = ','.join( header for header in headers )
csv_line = ','.join( str(dataset[key]) for key in dataset.keys() )
Example for a case of a dictionary mapping a string to a bunch of numbers.
- cpenner461 12y agoAny reason not to do the first one more compactly? ','.join(headers)
- elandybarr 12y agoOops. Good catch!
- marcinw 12y agoProper Python would use the csv module for this operation, as your CSV export would break if `header` or `dataset[key]` contains a comma.
- elandybarr 12y agoYeah. This was a special case for a one line CSV that was requested by my client. It was a dictionary with a bunch of single measurements.
- deleted 12y ago[deleted]
- rcfox 12y agoYou should just use dataset.values() (or itervalues if you're using Python 2) instead of iterating over the keys, and then looking them up.
- andreasvc 12y agoYou're relying on dataset.keys() being in the same order as headers. Really, you should use the csv module, even for one-line CSV files.