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

如何用Python将含3列的文本文件转换为嵌套字典形式的图

Convert Text Graph Data to Python Nested Dictionary

Got it, let's turn that text file into the nested dictionary graph you're after. Here's a clean, straightforward approach in Python that handles both file input and direct string data if you don't want to use a file.

Option 1: Read from a Text File

If your data is stored in a .txt file (let's call it graph_data.txt), use this code:

# Initialize empty graph dictionary
graph = {}

# Open and read the file (replace 'graph_data.txt' with your actual file path)
with open('graph_data.txt', 'r') as file:
    # Skip the header line so we don't process it as node data
    next(file)
    # Process each line in the file
    for line in file:
        # Strip whitespace and split the line into node and weight components
        from_node, to_node, weight = line.strip().split()
        # Convert weight from string to integer
        weight = int(weight)
        # Add the edge to the graph: create a sub-dict for the from_node if it doesn't exist
        if from_node not in graph:
            graph[from_node] = {}
        graph[from_node][to_node] = weight

# Verify the result (optional)
print(graph)

Option 2: Use Direct String Data

If you have the data as a string (instead of a file), you can process it directly like this:

# Your graph data as a multi-line string
graph_data = """#FromNodeId ToNodeId Weight
B A 5
B D 1
B G 2
A B 5
A D 3
A E 12
A F 5
D B 1
D G 1
D E 1
D A 3
G B 2
G D 1
G C 2
C G 2
C E 1
C F 16
E A 12
E D 1
E C 1
E F 2
F A 5
F E 2
F C 16"""

graph = {}
# Split the string into individual lines
lines = graph_data.strip().split('\n')
# Skip the first header line
for line in lines[1:]:
    from_node, to_node, weight = line.strip().split()
    weight = int(weight)
    # Build the nested dictionary structure
    if from_node not in graph:
        graph[from_node] = {}
    graph[from_node][to_node] = weight

# Check the output
print(graph)

How It Works

  • Skipping the Header: Both methods skip the first line (#FromNodeId ToNodeId Weight) since it's just metadata, not actual graph edges.
  • Processing Each Line: Each line is split into three parts: the starting node, target node, and weight. The weight gets converted to an integer because file/string input reads it as text by default.
  • Building the Nested Dict: For each starting node, we check if it's already in the main graph dict. If not, we create an empty sub-dictionary for it. Then we add the target node and its corresponding weight to that sub-dictionary.

Running either code will produce exactly the nested dictionary structure you specified.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:44:34