JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

Writing a dictionary to CSV in Python

Author:JIYIK Last Updated:2025/05/05 Views:

This tutorial will show you how to write a dictionary variable to a csv file in Python.


csvWriting a dictionary to a CSV file using the module in Python

The Python module csvcontains tools and functions for manipulating csv files. There are two simple methods that can be used to write a dictionary to a csv file. writer()and DictWriter().

The functions of these two methods are similar, the only difference is DictWriter()that is a wrapper class that contains more functions.

Let's set up an initial example with a dictionary with a few key-value pairs:

dct = {"Name": "John", "Age": "23", "Country": "USA"}

In the first example, we use writer()to access a new csv file and insert a dictionary into it.

import csv

dct = {"Name": "John", "Age": "23", "Country": "USA"}

with open("dct.csv", "w") as f:
    writer = csv.writer(f)
    for k, v in dct.items():
        writer.writerow([k, v])

Since the file access type is w, the contents of the csv file dct.csvwill be overwritten with the new changes. If the file does not exist then it will be automatically created in the same directory.

The contents of the csv file will be output:

CSV file

Since there is only one dictionary entry, the layout of the csv file contains all the keys in the first column and the values ​​in the second column.

Example using dictionary array

This is an example for a single dictionary. What if you want to insert multiple dictionaries into a csv file?

In this example, we will use the function DictWriter()to write to a csv file. The CSV layout from the first example also needs to be changed because there are multiple values ​​for the same key.

The first line should contain the key labels, and the following lines will contain the values ​​for each dictionary entry.

First, declare an array of dictionaries with the same key values.

dct_arr = [
    {"Name": "John", "Age": "23", "Country": "USA"},
    {"Name": "Jose", "Age": "44", "Country": "Spain"},
    {"Name": "Anne", "Age": "29", "Country": "UK"},
    {"Name": "Lee", "Age": "35", "Country": "Japan"},
]

Now write this array of dictionaries to a csv file using csvthe module .DictWriter()

import csv

labels = ["Name", "Age", "Country"]
dct_arr = [
    {"Name": "John", "Age": "23", "Country": "USA"},
    {"Name": "Jose", "Age": "44", "Country": "Spain"},
    {"Name": "Anne", "Age": "29", "Country": "UK"},
    {"Name": "Lee", "Age": "35", "Country": "Japan"},
]

try:
    with open("csv_dct.csv", "w") as f:
        writer = csv.DictWriter(f, fieldnames=labels)
        writer.writeheader()
        for elem in dct_arr:
            writer.writerow(elem)
except IOError:
    print("I/O error")

DictWriter()The arguments in fieldnamesare assigned to a variable labels, which is an array of dictionaries whose keys are arrays of labels.

It is also a good practice to wrap your file manipulation code with exception handling ( try ... except) to prevent external errors or incompatibilities with the file writing process.

Output:

CSV file array

All in all, csvthe module contains all the necessary functions and tools to write a dictionary to a csv file. This can be easily achieved using the functions writer()and .DictWriter()

Also note that you should wrap the blocks that manipulate files with exception handling to ensure that you catch the IO error before it corrupts anything.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Convert a list to a set in Python

Publish Date:2025/05/08 Views:144 Category:Python

This tutorial demonstrates how to convert a list to a set in Python. Difference between List and Set Lists and sets are standard Python data types that store values ​​in sequence. Python list stores comma separated values ​​between

Remove the first element from a list in Python

Publish Date:2025/05/08 Views:172 Category:Python

This tutorial will discuss different ways on how to remove the first element from a list. pop() Remove the first element from a list using the pop() Method can remove an element from a specific index. We have to specify the index from which

Convert a list to lowercase in Python

Publish Date:2025/05/08 Views:112 Category:Python

Lists can be used to store multiple items in a single variable. In Python, we can create a list of strings by enclosing the different elements in the list in single or double quotes. This tutorial demonstrates how to convert a list of strin

Remove all occurrences of an element from a Python list

Publish Date:2025/05/08 Views:69 Category:Python

In Python, lists allow the same element to appear multiple times. Even though the value of an element may be the same as other elements, each element will have a different index. Using these index numbers, you can easily access any element

Convert hex to bytes in Python

Publish Date:2025/05/08 Views:101 Category:Python

Hexadecimal, often abbreviated to hex, uses 16 symbols (0-9, a-f) to represent values, in contrast to the decimal system's 10. For example, 1000 in decimal is 3E8 in hexadecimal. Being proficient in dealing with hexadecimal is essential for

b in front of string in Python

Publish Date:2025/05/08 Views:53 Category:Python

This tutorial will discuss the statement in Python b" . b" Using the statement in Python b" The notation is used to specify strings in Python bytes . In contrast to regular strings with ASCII characters, bytes a string is an array of byte v

How to Convert Integer to Binary in Python

Publish Date:2025/05/08 Views:130 Category:Python

This tutorial explains how to convert an integer to binary in Python. This tutorial also lists some sample codes to illustrate different ways of converting from int to binary in Python. bin() Convert Int to Binary in Python using In Python,

How to convert an integer to bytes

Publish Date:2025/05/08 Views:77 Category:Python

Converting an integer int to a byte bytes is the inverse of bytes converting a byte to an integer . Most of the to methods int described in this article are the inverse of the to methods. int bytes bytes int Generic method for converting in

How to convert bytes to int in Python

Publish Date:2025/05/08 Views:111 Category:Python

Bytes The data type has a numerical range of 0~255 (0x00~0xFF). A byte has 8 bits of data, that's why its maximum value is 0xFF. In some cases, you need to convert a byte or byte array to an integer for further data processing. Let's see ho

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial