You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从.txt文件读取值后出现KeyError,求原因及解决方法

Fixing KeyError When Reading Graph Vertex Data from Text Files

Let's break down the problem first—your error comes from a mismatch in the data structure you're reading vs. what your code expects.

Looking at your program output:

[(1, 2, 3, 4, 5)]
[(1, 2), (1, 3), (2, 3), (3, 5), (5, 4)]

The first line shows that A (your vertex list) is a list containing a single tuple, not the flat list of integers [1,2,3,4,5] you had in your commented-out code.

Here's why that causes the KeyError:

  • When you initialize indegree and outdegree, you loop through elements in A. Right now, A only has one element: the tuple (1,2,3,4,5). So your dictionaries end up with one key: that entire tuple, not the individual integers 1,2,3,4,5.
  • Later, when you iterate over edges in B (like (1,2)), you try to increment outdegree[1]—but 1 isn't a key in outdegree (only the tuple is), hence the KeyError.

Two Easy Fixes:

1. Modify your v.txt file (cleanest solution)

Change the content of v.txt to be a flat list of integers instead of a list with a tuple:

[1,2,3,4,5]

This way, ast.literal_eval will read it directly into the same structure as your original commented-out V variable, and your code will work without changes.

2. Adjust the code to handle the existing file structure

If you can't edit the text file, add a line to unpack the tuple from the list:

import ast

with open('v.txt') as V:
    A = ast.literal_eval(V.read())
    # Unpack the tuple inside the list into a flat integer list
    A = list(A[0])  # Add this line

with open('e.txt') as E:
    B = ast.literal_eval(E.read())

print(A)
print(B)

indegree = {}
outdegree = {}

for x in A:
    indegree[x] = 0
    outdegree[x] = 0

for x,y in B:
    outdegree[x] += 1
    indegree[y] += 1

for x in A:
    print("Outdegree for vertex", x,"=", outdegree[x])
    print("Indegree for vertex", x,"=", indegree[x])

After either fix, A will be the flat integer list your code expects, and the KeyError will disappear.

内容的提问来源于stack exchange,提问作者teddy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:53:52