Python: I have a list of dictionaries but when I try to call a specific Key and Value it is throwing a error

def readParksFile(fileName="national_parks(1).csv"):
    nationalParks = open(fileName)
    headers = nationalParks.readline()
    keys = headers.split(",")
    numKeys = len(keys)
    parksList = []
    values = nationalParks.readlines()
    rowsList = []
    parksDictionary = {}
    for row in values:
    for item in rowsList:
        parksDictionary = {}
        for i in range(numKeys):
            parksDictionary[keys[i]] = item[i]
    for i in range(len(parksList)):


I created a list of dictionaries using the code above

def printParksInState(parksList):
    state = getStateAbbr()
    for parksDictionary in parksList:
        if state in parksDictionary["State"]:
            print(parksDictionary["Name"] + " (" + parksDictionary["Code"] + ")")
            print("\t" + "Location:" + parksDictionary["State"])
            print("\t" + "Area:" + parksDictionary["Acres"] + " acres")
            print("\t" + "Date Established:" + tasks.convertDate(parksDictionary["Date"]))
            print("There are no national parks in " + state + " or it is not a valid state")

I have functions that uses the list of dictionaries to print information

def main():
    print("National Parks")

    parksList = tasks.readParksFile()
    menuDict = interface.getMenuDict()

    choice = ("")
    while choice != "Q":
        choice = interface.getUserChoice(menuDict)
        if choice == "A":
        elif choice == "B":
        elif choice == "C":
        elif choice == "D":
            print("This is not an option")

In my main function I call the other functions that uses the list of dictionaries

Error However no matter what function I call it throws the error that string indices must be integers and I am not sure what this error is or how to fix it. Please help!

1 answer

  • answered 2022-05-07 00:11 Samwise

    The error is telling you that parksDictionary isn't a dict, it's a str.

    The bug is in readParksFile, which is only returning a single item:

        for i in range(len(parksList)):

    It should instead just do:

        return parksList

    As soon as you return, the function is done, so you can only return one thing, and you should close() the file before then.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum