Writing a dictionary to a csv file with one line for every 'key: value'
The DictWriter
doesn't work the way you expect.
with open('dict.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
for key, value in mydict.items():
writer.writerow([key, value])
To read it back:
with open('dict.csv') as csv_file:
reader = csv.reader(csv_file)
mydict = dict(reader)
which is quite compact, but it assumes you don't need to do any type conversion when reading
How to write dictionary to a csv file with one line for every 'key: value' and serial number of keys?
Do not add '\t'
yourself. Instead, use the delimiter
argument of csv.writer
.
As a bonus, this code:
- Uses
with
- Cleans all the conversions to
str
withmap
- Opens the file with
newline=''
becuasecsv.writer
tends to add line breaks
import csv
d = {"(2,3,4)": '3', "(201,233,207)": '23', "(176,247,207)": '78'}
with open("data.csv", "w", newline='') as f:
w = csv.writer(f, delimiter='\t')
w.writerow(map(str, (0, 'xval', 'yval')))
for counter, (key, val) in enumerate(d.items(), 1):
w.writerow(map(str, (counter, key, val)))
When opening the file in Excel or any other spreadsheet application make sure to choose tabs as the delimiter.
I haven't used Python 2.7 in ages. I hope this does not terribly fail.
Write dictionary to csv with one line per value
This is because [key, value]
contains multiple "values" within value
. Try iterating over the dictionary like this:
for key, values in foo.items():
for value in values:
writer.writerow([key, value])
Write dict of dict to CSV with one key/value per row with keys filling columns
You need to use the value from each loop as the thing to iterate through in the next loop. Also, both loops need to use items()
, not keys()
.
for key, value in d.items():
for inner_key, inner_value in value.items():
for item in inner_value:
writer.writerow(key, inner_key, item)
Python: Write dictionary with multiple rows to CSV
import csv
with open('data.csv', 'w') as outfile:
writer = csv.DictWriter(outfile, ['Commodities', 'Area', 'Type'], delimiter=';')
writer.writeheader()
for l in links:
...
print(d)
writer.writerow(d)
Related Topics
Parsing Datetime Strings Containing Nanoseconds
How to Print Bold Text in Python
What's the Fastest Way in Python to Calculate Cosine Similarity Given Sparse Matrix Data
Format Floats with Standard JSON Module
Run Command and Get Its Stdout, Stderr Separately in Near Real Time Like in a Terminal
How to Compare String and Integer in Python
Difference Between Numpy Dot() and Python 3.5+ Matrix Multiplication @
Consistently Create Same Random Numpy Array
"Line Contains Null Byte" in CSV Reader (Python)
Calculate Area of Polygon Given (X,Y) Coordinates
Pycharm Doesn't Recognise Installed Module
Compute a Confidence Interval from Sample Data
Check If a String in a Pandas Dataframe Column Is in a List of Strings