'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:
rowsList.append(row.split(","))
for item in rowsList:
parksDictionary = {}
for i in range(numKeys):
parksDictionary[keys[i]] = item[i]
parksList.append(parksDictionary)
for i in range(len(parksList)):
return(parksList[i])
nationalParks.close()
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"]))
else:
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":
print(interface.displayMenu(menuDict))
choice = interface.getUserChoice(menuDict)
if choice == "A":
interface.printAllParks(parksList)
elif choice == "B":
interface.printParksInState(parksList)
elif choice == "C":
interface.printLargestPark(parksList)
elif choice == "D":
interface.printParksForSearch(parksList)
else:
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!
Solution 1:[1]
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)):
return(parksList[i])
It should instead just do:
nationalParks.close()
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Samwise |
