2012-03-02 25 views
0

我需要能夠通過郵編搜索字典,但我不斷收到TypeError: sliced indices must be integers or None or have an __index__ method。 我不確定如何整合__index__方法。 這裏是我的代碼:從csv創建字典,需要密鑰是郵政編碼

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() 

如果我在dicts = {'zip code': row[1],'latitude': row[2], 'longitude': row[3]} 一切正常交換,但它打印Latitude:xxxxx zipcode:xxxxx longitude:xxxxx,我需要它來按郵政編碼的結構。

+0

有很多在'try'塊語句。儘可能保持'try'塊不變,這樣你就不會意外地忽略你不期望的異常。 – 2012-03-02 21:18:15

+0

你打算存儲在「字典」,列表或字典從郵編到座標? – dsign 2012-03-02 21:19:41

+0

郵政編碼與他們各自的座標,然後我需要編寫一個代碼來過濾通過在用戶輸入的郵政編碼的50英里內的郵編 – matture 2012-03-02 21:21:21

回答

2

你的代碼基本上是一個語法錯誤。你想用dicts['zip code':row[0]]做什麼?

Python認爲你正在使用切片運算符,就像你會得到像some_list[2:5]這樣的列表的中間部分(它返回索引2到索引4的some_list的項目)。 'zip code'不能用作分片索引,因爲它不是數字。

我想你想做的事:

dicts = {} 

通過與{}聲明dicts這是一本字典,所以你可以使用你的郵政編碼爲按鍵。

然後:

 dicts[row[0]] = {'latitude': row[2], 'longitude': row[3]} 

或許

 zip_code = row[0] 
    dicts[zip_code] = {'zip code': zip_code, 'latitude': row[2], 'longitude': row[3]} 

然後,您可以訪問與dicts['91010']的郵政編碼91010的信息:

>>> print dicts['91010']['latitude'] 
'-34.12N' 
+0

我更新了我的答案,更清楚地解釋爲什麼要使用'dicts = {}' – 2012-03-02 21:26:57

+0

zipcode = row [0] .strip() dicts [zipcode] = {'latitude':row [2] .replace(''','').strip(),'longitude':row [3] .replace('「 ','')。(){ print dicts ['10306'] ['latitude'] – matture 2012-03-02 21:53:26

+0

多數民衆贊成我當前的代碼,但它給了我關鍵字錯誤:'10306' – matture 2012-03-02 21:53:48

1

這定義了通過索引來訪問列表:

dicts = [] 
dicts[0] = 'something' 

這將定義哪些是鍵訪問字典:

dicts = {} # curly braces 
dicts['key'] = 'value' 

我的猜測是,一個{}是什麼你要。

0

問題出在線dicts[zip code:row[0]]。您正在嘗試使用列表,就好像它是一本字典。

0

取而代之的是:

{'zip code': xxx, 'latitude': xxx, 'longitude': xxx } 

這樣做:

{'xxx' : { 'latitude': xxx, 'longitude': xxx } } 
#zipcode