I need to be able to search through the dictionary by zipcode but I keep getting a TypeError: sliced indices must be integers or None or have an __index__ method.
I’m not sure how to integrate the __index__ method.
Here is my code:
import sys
import csv
import re
dicts = []
def getzip():
try:
f = open("zips.csv")
csvParser = csv.reader(f)
for row in csvParser:
dicts['zip code':row[0]] = {'latitude': row[2], 'longitude': row[3]}
print dicts
except ValueError:
pass
getzip()
If I swap in dicts = {'zip code': row[1],'latitude': row[2], 'longitude': row[3]}
everything works but it prints Latitude:xxxxx zipcode:xxxxx longitude:xxxxx and I need it to be structured by zipcode.
Your code is basically a syntax error. What are you trying to do with
dicts['zip code':row[0]]?Python thinks you’re using the slice operator, like you would to get a middle portion of a list like
some_list[2:5](which returns items from index 2 through index 4 ofsome_list).'zip code'doesn’t work as a slice index, since it’s not a number.I think you want to do:
By declaring
dictswith{}it’s a dictionary, so you can use your zip codes as keys.Then:
or perhaps
You could then access the information for zip code 91010 with
dicts['91010']: