Home > Blockchain >  Python: How to convert CSV file to lists of dictionaries without importing reader or external librar
Python: How to convert CSV file to lists of dictionaries without importing reader or external librar

Time:05-06

I need to convert a CSV file into a list of dictionaries without importing CSV or other external libraries for a project I am doing for class.
Attempt I am able to get the keys using header line but when I try to extract the values it goes row by row instead of column by column and starts in the wrong place. However when I append it to the list it goes back to starting at the right place. However I am unsure of how to connect the keys to the correct column in the list.
CSV file This is the CSV file I am using, I am only using the descriptions portion up to the first comma.
I tried using a for 6 loop in order to cycle through each key but it seems to go row by row and I don't know how to change it.
If anybody could steer me in the right direction it would be very appreciated.

CSV sample - sample is not saving correctly but it has the three headers on top and then the three matching information below and so on.
(Code,Name,State)\n (ACAD,Acadia National Park,ME)\n (ARCH,Arches National Park,UT)\n (BADL, Badlands National Park,SD)\n

CodePudding user response:

read your question. I am posting code from what I understood from your question. You should learn to post the code in question. It is a mandatory skill. Always open a file using the "with" block. I made a demo CSV file with two rows of records. The following code fetched all the rows as a list of dictionaries.

def readParksFile(fileName="national_parks.csv"):
    with open(fileName) as infile:
        column_names = infile.readline()
        keys = column_names.split(",")
        number_of_columns = len(keys)
        list_of_dictionaries = []
        data = infile.readlines()
        list_of_rows = []
        for row in data:
            list_of_rows.append(row.split(","))
        infile.close()
        for item in list_of_rows:
            row_as_a_dictionary = {}
            for i in range(number_of_columns):
                row_as_a_dictionary[keys[i]] = item[i]
            list_of_dictionaries.append(row_as_a_dictionary)

    for i in range(len(list_of_dictionaries)):
        print(list_of_dictionaries[i])

Output:

{'Code': 'cell1', 'Name': 'cell2', 'State': 'cell3', 'Acres': 'cell4', 'Latitude': 'cell5', 'Longitude': 'cell6', 'Date': 'cell7', 'Description\n': 'cell8\n'}
{'Code': 'cell11', 'Name': 'cell12', 'State': 'cell13', 'Acres': 'cell14', 'Latitude': 'cell15', 'Longitude': 'cell16', 'Date': 'cell17', 'Description\n': 'cell18'}

CodePudding user response:

I would create a class with a constructor that has the keys from the first row of the CSV as properties. Then create an empty list to store your dictionaries. Then open the file (that is a built-in library so I assume you can use it) and read it line by line. Store the line as a string and use the split method with a comma as the delimiter and store that list in a variable. Call the constructor of your class for each line to construct your dictionary using the indexes of the list from the split method. Before reading the next line, append the dictionary to your list. This is probably not the easiest way to do it but it doesn't use any external libraries (although as others have mentioned, there is a built-in CSV module).

Code:

#Class with constructor
class Park:
  def __init__(self, code, name, state):
    self.code = code
    self.name = name
    self.state = state

#Empty array for storing the dictionaries
parks = []

#Open file
parks_csv = open("parks.csv")

#Skip first line
lines = parks_csv.readlines()[1:]

#Read the rest of the lines
for line in lines:
    parkProperties = line.split(",")
    newPark = Park(parkProperties[0], parkProperties[1], parkProperties[2])
    parks.append(newPark)

#Print park dictionaries
#It would be easier to parse this using the JSON library
#But since you said you can't use any libraries
for park in parks:
    print(f'{{code: {park.code}, name: {park.name}, state: {park.state}}}')

#Don't forget to close the file
parks_csv.close()

Output:

{code: ACAD, name: Acadia National Park, state: ME}
{code: ARCH, name: Arches National Park, state: UT}
{code: BADL, name:  Badlands National Park, state: SD}
  • Related