如果字典中不存在键,如何跳至下一个条目

时间:2019-05-14 19:10:08

标签: python dictionary

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

如果在字典中找不到密钥,请跳过

编辑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'

任何帮助/建议都将受到高度赞赏。 谢谢

3 个答案:

答案 0 :(得分:1)

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

if vertex not in graph:
    continue

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

答案 1 :(得分:1)

您可以在执行最终的for循环之前检查顶点是否在图形中:

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

答案 2 :(得分:1)

您可以执行一个.get并返回一个空的{},以防密钥不存在,以使.items()不会损坏,

for (next_v, d) in graph.get(vertex, {}).items():
    heapq.heappush(queue, (distance + d, next_v, path))
相关问题