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)

And this is the csv that was generated:


CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top