2012-03-02 27 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