Writing a Dictionary to a CSV File with One Line for Every 'Key: Value'

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 delimiterargument of csv.writer.

As a bonus, this code:

  • Uses with
  • Cleans all the conversions to str with map
  • Opens the file with newline='' becuase csv.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



Leave a reply



Submit