如何将BFS输出的多个字典插入到空字典中?
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

