python - 如果字典中不存在键,我如何跳到下一个条目
问题描述
我有一个字典,但给定的条目可能不存在。例如,我有以下字典,其中c
缺少条目:
g = {
'a': {'w': 14, 'x': 7, 'y': 9},
'b': {'w': 9, 'c': 6}, # <- c is not in dict
'w': {'a': 14, 'b': 9, 'y': 2},
'x': {'a': 7, 'y': 10, 'z': 15},
'y': {'a': 9, 'w': 2, 'x': 10, 'z': 11},
'z': {'b': 6, 'x': 15, 'y': 11}
}
我当前的代码
start = 'a'
end = 'z'
queue, seen = [(0, start, [])], set()
while True:
(distance, vertex, path) = heapq.heappop(queue)
if vertex not in seen:
path = path + [vertex]
seen.add(vertex)
if vertex == end:
print(distance, path)
break # new line, based on solutions below
# new line
if vertex not in graph: # new line
continue # new line
for (next_v, d) in graph[vertex].items():
heapq.heappush(queue, (distance + d, next_v, path))
现在我收到错误:
for (next_v, d) in graph[vertex].items():
KeyError: 'c'
编辑 1
如果在 dict 中找不到键,则向前跳过。
编辑 2
即使使用新添加的代码,我也会收到错误,这一次:
(distance, vertex, path) = heapq.heappop(queue)
IndexError: index out of range
这是我使用的数据文件
https://s3-eu-west-1.amazonaws.com/citymapper-assets/citymapper-coding-test-graph.dat
这是文件格式:
<number of nodes>
<OSM id of node>
...
<OSM id of node>
<number of edges>
<from node OSM id> <to node OSM id> <length in meters>
...
<from node OSM id> <to node OSM id> <length in meters>
这是创建图表的代码
with open(filename, 'r') as reader:
num_nodes = int(reader.readline())
edges = []
for line in islice(reader, num_nodes + 1, None):
values = line.split()
values[2] = int(values[2])
edges.append(tuple(values))
graph = {k: dict(x[1:] for x in grp) for k, grp in groupby(sorted(edges), itemgetter(0))}
更改start
为end
:
start = '876500321'
end = '1524235806'
非常感谢任何帮助/建议。谢谢
解决方案
在访问之前graph[vertex]
,请确保它在字典中:
if vertex not in graph:
continue
for (next_v, d) in graph[vertex].items():
heapq.heappush(queue, (distance + d, next_v, path))
推荐阅读
- javascript - HandleKeyPress 无法识别向下箭头
- python - Plotly:如何在 x 轴上仅绘制月份和日期?(忽略年份)
- javascript - 您可以在 Google Script 中为 array.forEach 添加标签吗?
- python - Numpy多项式生成
- c# - 生成字母数字 50 字符长 GUID 的更好方法
- go - 如何使用 Colly 在 Golang 中将字符串解析为 DOM 元素
- java - Spring boot 中的 RestController - 404 ERROR 而不是 JSON 对象
- javascript - 从选择菜单中选择新位置时,如何从谷歌地图中删除图钉?
- smartcard - 使用 ant-javacard 构建 JavaCard 库
- java - 二元运算真值表