Skip to content
Advertisement

How can you properly put a dictionary into a CSV file so you can search the CSV File by key values?

I am attempting to put a dictionary which has two properties of ID and Status into a CSV file. After putting it into the CSV file correctly I am wanting to search for a certain row by ID, then return the Status that is tied to that row’s ID. The issue I am having is that during the for loop during the read, the row is a dictionary with ‘ID,Status’: ‘1,Off’. Since the field names and values are all together I can’t really filter by a specific ID or grab a specific Status. I would like each row to be like ‘ID’: 1, ‘Status’: ‘Off’ I am either putting the dictionary in wrong or attempting to read it wrong using a for loop. Any pointers would be greatly appreciated since I’m still pretty new with CSV files! Thanks!

This is currently what I am using. It checks if the Csv file exists, if not, it creates and populates it, then attempts to read the data it needs. Otherwise it just attempts to get the data it needs based on an ID passed in.

fields = ['ID', 'Status']
dict_data = [
    {'ID': 1, 'Status': 'Off'},
    {'ID': 2, 'Status': 'Off'},
    {'ID': 3, 'Status': 'Off'}
]
    file_exists = os.path.exists("ports.csv")
    if file_exists:
        with open(filename, 'r') as csvfile:
            reader = csv.DictReader(csvfile, delimiter=' ')
            for row in reader:
                if row['ID'] == int(id):
                    port_status = row['Status']
    else:
        with open(filename, 'w', newline='') as file:
            writer = csv.DictWriter(file, fieldnames=fields)
            writer.writeheader()
            for data in dict_data:
                writer.writerow(data)

        with open(filename, 'r') as csvfile:
            reader = csv.DictReader(csvfile, delimiter=' ')
            for row in reader:
                if row['ID'] == int(id):
                    port_status = row['Status']
    response = {
        port_status
    }
    return jsonify(response)

Advertisement

Answer

In the process of trying to test the code & do some cleanup I fixed it.

import csv
import os

def find_row_by_id(csvfile, input_id):
        port_status = None
        reader = csv.DictReader(csvfile)
        for row in reader:
                print(f"ROW: {row}")
                if int(row['ID']) == int(input_id):
                        port_status = row['Status']
        return port_status


fields = ['ID', 'Status']
dict_data = [
    {'ID': 1, 'Status': 'Off'},
    {'ID': 2, 'Status': 'Off'},
    {'ID': 3, 'Status': 'Off'}
]
input_id = 3
filename = 'ports.csv'
file_exists = os.path.exists(filename)
if not file_exists:
        with open(filename, 'w', newline='') as file:
            writer = csv.DictWriter(file, fieldnames=fields)
            writer.writeheader()
            for data in dict_data:
                writer.writerow(data)

with open(filename, 'r') as csvfile:
        pstatus = find_row_by_id(csvfile, input_id)

response = {
        pstatus
}

print(response)

A few changes I made:

  • Got rid of the duplicate read code & put it in a function.
  • id is a Python reserved word, so I replaced it with input_id.
  • I removed the delimiter argument to your DictReader constructor. I did this because I couldn’t remember what that argument did & rather than look it up I just wanted to try it. This could’ve been the fix.
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement