'Write dict to csv with integers as keys

I have a dict with epoch times as keys. It looks like this:

my_dict = {199934234: "val1", 1999234234: "val2"}

When trying to write it to a csv, I get the error "iterable expected, not int". There is no problem, however, when using regular keys.

import csv

with open('my_file.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(my_dict)

I want to write it to a csv so that I can load it at a later point again as a dictionary so that I can update it ... and then write it to a csv again. The csv will be accessed by my website later on.

What would be the best solution to do this? In any other case I would use rrd but in this case I do not have irregular update times.



Solution 1:[1]

Try:

with open("output.csv", "w", newline="") as csvfile:
    writer = csv.writer(csvfile)
    for k, v in my_dict.items():
        writer.writerow([k, v])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 not_speshal