Home > Backend Development > Python Tutorial > How to Create a Single Dictionary from a CSV File Using Python?

How to Create a Single Dictionary from a CSV File Using Python?

Barbara Streisand
Release: 2024-11-19 22:51:03
Original
630 people have browsed it

How to Create a Single Dictionary from a CSV File Using Python?

Creating a Dictionary from a CSV File:

Attempting to create a dictionary from a CSV file using the csv.DictReader and csv.DictWriter classes can result in multiple dictionaries being generated. However, the goal is to create a single dictionary that accurately captures the key-value pairs present in the CSV file.

Solution:

The syntax to accomplish this is concise and efficient. Using list comprehension, the first element of each row (key) can be paired with the second element (value) to form a dictionary. Here's the updated code:

import csv

with open('coors.csv', mode='r') as infile:
    reader = csv.reader(infile)
    with open('coors_new.csv', mode='w') as outfile:
        writer = csv.writer(outfile)
        mydict = {rows[0]:rows[1] for rows in reader}
Copy after login

Alternatively, for Python versions less than or equal to 2.7.1:

mydict = dict((rows[0],rows[1]) for rows in reader)
Copy after login

This code effectively reads each row of the CSV file, associates the first element as the key, and the second element as the value. The resulting mydict variable is a comprehensive dictionary that encompasses all the key-value pairs from the input file. By adopting this approach, you can effortlessly create a dictionary from a CSV file, providing a convenient way to organize and access the data.

The above is the detailed content of How to Create a Single Dictionary from a CSV File Using Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template