0

I checked the topic: Writing multiple Python dictionaries to csv file but I think it does not answer my question yet.

I have several dictionaries like:

{day:1, temperature: 30}
{day:2, temperature: 40}

and so on

The dictionaries are not ready at once but are downloaded through a scheduler.

I want to write to a file as:

day temperature
1 30
2 40

and continue to append to the file when new dictionaries come in.

How could I do that with Python 3?

Thank you very much,

jpp
  • 159,742
  • 34
  • 281
  • 339
mommomonthewind
  • 4,390
  • 11
  • 46
  • 74

1 Answers1

3

Using the csv module and an iterable of dictionaries L:

import csv

L = [{'day': 1, 'temperature': 30},
     {'day': 2, 'temperature': 40}]

with open(r'c:\temp\out.csv', 'w', newline='') as f:
    wr = csv.writer(f)
    wr.writerow(['day', 'temperature'])
    for item in L:
        wr.writerow([item['day'], item['temperature']])

Result:

day,temperature
1,30
2,40
jpp
  • 159,742
  • 34
  • 281
  • 339