how do you write python dictionary in csv if the order of keys and values varies?

Use a csv.DictWriter. The fieldnames will force the order.

import csv
data = [
    {
        "id": 1,
        "name": "Peter",
        "city": "London"
    },
    {
        "id": 2,
        "city": "Boston",
        "name": "Paul"

    },
    {
        "id": 3,
        "name": "Mary",
        "city": "Paris"
    }
]
with open('test.csv', "w", newline='', encoding='utf-8') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames=["id", "name", "city"], delimiter=',', quoting=csv.QUOTE_ALL)
    writer.writerows(data)

And this is the csv that was generated:

"1","Peter","London"
"2","Paul","Boston"
"3","Mary","Paris"

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top