使用数组生成dict时出现键错误

2024-09-28 22:09:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图构建两个dict,一个具有偶数街道值,另一个具有奇数街道值。每个街道都有一个Ref_ID,我希望每个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中转换if str(row[0]),但没有成功。在


Tags: oftheinstreetforif街道cursor
1条回答
网友
1楼 · 发布于 2024-09-28 22:09:29

问题可能在于嵌套的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

相关问题 更多 >