使用数组构建dict时出现键错误

时间:2017-01-31 22:27:03

标签: python dictionary multidimensional-array arcpy

我正在尝试构建两个dicts,一个具有偶数街道值,另一个具有奇数街道值。每条街道都有一个Ref_ID,我希望每个dict都使用这些值作为键,并将相应的序列号作为值。

我看到一个以前的帖子用数组作为值来制作一个dict: append multiple values for one key in Python dictionary

我尝试在我的代码中执行此操作,但我认为偶数和奇数的条件以及使用arcpy.SearchCursor会给代码增加一些复杂性:

import arcpy

#service location layer
fc = r"J:\Workspace\FAN3 sequencing3\gisdb\layers.gdb\Rts_239_241_314_GoLive"

# create variables

f1 = "Route"
f2 = "Ref_ID"
f3 = "Sequence"
f4 = "Street_Number"

# create containers

rSet = set()
eLinks = dict()
oLinks = dict()

# make a route list

with arcpy.da.SearchCursor(fc, f1) as cursor:
    for row in cursor:
        rSet.add(row[0])
    del row

# list of even side street sequences
eItems = []
eCheckStreet = []

# list of odd side street sequences
oItems = []
oCheckStreet = []

# make two dicts, one with links as keys holding sequence values for the even side of the street
# the other for the odd side of the street

for route in rSet:
    with arcpy.da.SearchCursor(fc, [f2,f3,f4]) as cursor:
        for row in cursor:
            if row[2] != '0' and int(row[2]) % 2 == 0:
                if row[0] in eLinks:
                    eLinks[str(row[0])].append(row[1])
                else:
                    eLinks[str(row[0])] = [row[0]]
            elif row[2] != '0' and int(row[2]) % 2 != 0:
                if row[0] in eLinks:
                    oLinks[str(row[0])].append(row[1])
                else:
                    oLinks[str(row[0])] = [row[0]]
        del row

print eLinks, oLinks

输出是Ref_ID作为键和值。我已经尝试改变索引,看看我是否会得到不同的东西,但它仍然是相同的。我也试过在eLinks中转换str(row [0])但无效。

1 个答案:

答案 0 :(得分:0)

问题可能出在嵌套if以及这些条件如何相互影响。您不必担任字典上标准密钥检查的责任:您可以使用内置数据结构:collections.defaultdicthttps://docs.python.org/2/library/collections.html#collections.defaultdict

import arcpy
from collections import defaultdict

#service location layer
fc = r"J:\Workspace\FAN3 sequencing3\gisdb\layers.gdb\Rts_239_241_314_GoLive"

# create variables

f1 = "Route"
f2 = "Ref_ID"
f3 = "Sequence"
f4 = "Street_Number"

# create containers

rSet = set()
eLinks = defaultdict(list)
oLinks = defaultdict(list)

# make a route list

with arcpy.da.SearchCursor(fc, f1) as cursor:
    for row in cursor:
        rSet.add(row[0])
    del row


# make two dicts, one with links as keys holding sequence values for the even side of the street
# the other for the odd side of the street

for route in rSet:
    with arcpy.da.SearchCursor(fc, [f2,f3,f4]) as cursor:
        for row in cursor:
            if row[2] != '0' and int(row[2]) % 2 == 0:
                eLinks[str(row[0])].append(row[1])
            elif row[2] != '0' and int(row[2]) % 2 != 0:
                oLinks[str(row[0])].append(row[1])
        del row
print eLinks, oLinks