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

Python存储嵌套字典列表键路径及回读的实现方法咨询

Got it, let's work through this problem together. You need to crawl a deeply nested list of dictionaries (your system info data) to record full key paths like .children[0].children[9].children[0].children[0].handle mapped to their values, plus be able to fetch values back using those paths. Here's a straightforward Python implementation that does exactly that:


1. Generate Full Paths & Store Key-Value Pairs

First, we'll build a recursive function to traverse your nested data. It'll track the full path to each leaf value and store everything in a dictionary for easy access later.

def generate_path_map(data, current_path="", path_map=None):
    # Initialize the path map if it's the first call
    if path_map is None:
        path_map = {}
    
    # Handle nested lists (like your .children[index] entries)
    if isinstance(data, list):
        for idx, item in enumerate(data):
            # Append the list key and index to the current path
            new_path = f"{current_path}.children[{idx}]" if current_path else f"children[{idx}]"
            generate_path_map(item, new_path, path_map)
    
    # Handle nested dictionaries
    elif isinstance(data, dict):
        for key, value in data.items():
            # Append the dict key to the current path
            new_path = f"{current_path}.{key}" if current_path else key
            # If the value is another nested structure, keep traversing
            if isinstance(value, (dict, list)):
                generate_path_map(value, new_path, path_map)
            # If it's a leaf value, save the full path and value
            else:
                path_map[new_path] = value
    
    return path_map

How this works:

  • It starts at your root data structure and builds paths incrementally.
  • For lists, it adds .children[index] (matching your sample path format) to the path string.
  • For dictionary keys, it adds .key to the path.
  • When it hits a non-nested value (like PCI:0000:01:00.0), it stores the complete path and value in path_map.

2. Retrieve Values Using Full Paths

Next, we'll write a function to parse those stored paths and fetch the corresponding value from the original nested data.

def get_value_by_path(data, path):
    current_node = data
    # Split the path into individual steps (e.g., ["children[0]", "children[9]", "handle"])
    path_steps = path.split(".")
    
    for step in path_steps:
        # Check if the step is a list index (like "children[0]")
        if "[" in step and "]" in step:
            list_key, idx_str = step.split("[")
            idx = int(idx_str.rstrip("]"))
            # Navigate into the list
            if isinstance(current_node, dict) and list_key in current_node:
                current_node = current_node[list_key][idx]
            else:
                raise KeyError(f"Could not find list key '{list_key}' or index '{idx}'")
        # Otherwise it's a dictionary key (like "handle" or "product")
        else:
            if isinstance(current_node, dict) and step in current_node:
                current_node = current_node[step]
            else:
                raise KeyError(f"Could not find key '{step}'")
    
    return current_node

How this works:

  • It splits the path string into individual steps.
  • For list steps (like children[0]), it extracts the list key and index, then navigates to that position in the data.
  • For dictionary keys, it directly accesses the key in the current node.
  • If any step can't be found, it raises a clear KeyError to help debug.

3. Test with Your Sample Data

Let's use your example data to verify the code works:

# Sample nested data matching your path examples
system_data = [
    {
        "children": [
            {},  # children[0]
            {},
            # ... skip to children[9]
            {
                "product": "Xeon E7 v4/Xeon E5 v4/Xeon E3 v4/Xeon D DMI2",
                "children": [
                    {
                        "children": [
                            {
                                "handle": "PCI:0000:01:00.0",
                                "description": "Non-Volatile memory controller",
                                "product": "Samsung Electronics Co Ltd"
                            }
                        ]
                    }
                ]
            }
        ]
    },
    {},
    {
        "product": "PWS-406P-1R N..."
    }
]

# Generate the path map
path_map = generate_path_map(system_data)

# Check a stored path
print(path_map[".children[0].children[9].children[0].children[0].handle"])
# Output: PCI:0000:01:00.0

# Fetch a value using the path
print(get_value_by_path(system_data, ".children[2].product"))
# Output: PWS-406P-1R N...

Quick Customization Tip

If your nested lists use a key other than children, just modify the list path generation line in generate_path_map to use your actual list key (e.g., f"{current_path}.devices[{idx}]" instead of children).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:49:43