首页 > 解决方案 > 如果字典中不存在键,我如何跳到下一个条目

问题描述

我有一个字典,但给定的条目可能不存在。例如,我有以下字典,其中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))}

更改startend

start = '876500321'
end = '1524235806'

非常感谢任何帮助/建议。谢谢

标签: pythondictionary

解决方案


在访问之前graph[vertex],请确保它在字典中:

if vertex not in graph:
    continue

for (next_v, d) in graph[vertex].items():
    heapq.heappush(queue, (distance + d, next_v, path))

推荐阅读