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

如何生成嵌套字典的扁平化键列表并按字母顺序排序?

Solution to Generate Sorted Flattened Nested Dictionary Fields

Got it, let's tackle this problem. Generating a list of all nested field names (joined with dots) and sorting them alphabetically is straightforward with a recursive approach—here's how you can do it in Python:

Step-by-Step Implementation

First, write a recursive function that traverses every level of your nested dictionary, builds the full field path as it goes, and collects all the leaf node paths. Then we'll sort the final list.

def flatten_and_sort_fields(nested_dict, parent_path="", separator="."):
    field_list = []
    for key, value in nested_dict.items():
        # Build the full path for the current key
        full_path = f"{parent_path}{separator}{key}" if parent_path else key
        
        # If the value is another dictionary, recurse into it
        if isinstance(value, dict):
            field_list.extend(flatten_and_sort_fields(value, full_path, separator))
        # If it's a leaf value, add the full path to our list
        else:
            field_list.append(full_path)
    
    # Sort the list alphabetically before returning
    return sorted(field_list)

How It Works

Let's break down what this function does:

  • Initialization: We start with an empty list to hold our field paths.
  • Path Building: For each key in the current dictionary, we construct the full path by appending the key to the parent path (using the dot separator, unless it's the top-level key).
  • Recursion: If the value associated with the key is another dictionary, we recursively call the function with this sub-dictionary and the new full path as the parent.
  • Leaf Collection: When we hit a non-dictionary value (a leaf node), we add the full path to our list.
  • Sorting: Finally, we return the sorted list of field paths.

Example Usage

Let's test this with a sample nested dictionary:

# Sample nested dictionary
my_data = {
    "customer": {
        "personal_info": {
            "first_name": "John",
            "last_name": "Doe"
        },
        "billing": {
            "address": "123 Main St",
            "payment_method": "credit_card"
        }
    },
    "order": {
        "id": "ORD-1234",
        "status": "shipped"
    }
}

# Get the sorted flattened fields
result = flatten_and_sort_fields(my_data)
print(result)

Output

['customer.billing.address', 'customer.billing.payment_method', 'customer.personal_info.first_name', 'customer.personal_info.last_name', 'order.id', 'order.status']

Notes

  • If your nested structure includes lists (e.g., customer.addresses[0].city), you'll need to adjust the function to handle list indices—let me know if you need help with that!
  • The function assumes all nested non-leaf nodes are dictionaries. If you have other iterable types (like tuples), you'll want to add checks for those as needed.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:16:45