使用数组构建字典时出现关键错误

key error when building dict with arrays

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

我看到一个前者post用数组作为值来制作字典: 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 中转换 if str(row[0]) 但无济于事。

问题可能出在嵌套 if 以及这些条件如何相互作用。您不必承担对字典进行标准键检查的责任:有一个 built-in 数据结构可以做到这一点:collections.defaultdict: https://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