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

如何将BFS输出的多个字典插入到空字典中?

Solution to Collect BFS Results into a Nested Dictionary

Hey there! Let's get your BFS results organized into that nested dictionary you want. From what you described, the main issue is likely that you're only printing the BFS outputs instead of storing them directly into your empty dictionary. Here's how to fix it step by step:

Step 1: Initialize an empty dictionary

First, create an empty dict to hold all your results. This will be our final nested dictionary where keys are the starting nodes, and values are the corresponding BFS output dictionaries.

bfs_results = {}

Step 2: Iterate through nodes and store results

Instead of just printing the BFS output, assign each result directly to the dictionary using the current node as the key. This replaces your original print loop with a storage loop:

for node in graph.keys():
    # Assign the BFS result to the node key in our dictionary
    bfs_results[node] = BFS(graph, node)

Step 3: Use your nested dictionary

Once the loop finishes, bfs_results will be exactly the nested structure you want. You can print it, access specific node results, or use it for further processing:

# Print the full nested dictionary
print(bfs_results)

# Access the BFS result for a specific node, e.g., node 'A'
print(bfs_results['A'])

Why your previous attempt might have failed

Chances are you either:

  • Forgot to assign the BFS return value to the dictionary (only printed it instead), or
  • Tried using list methods like append() on the dictionary (which doesn't work—dictionaries use key-value assignments instead).

As long as your BFS() function returns a dictionary for each starting node, this approach will work perfectly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:26:59