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

如何将扁平化字典转换为任意深度的嵌套字典?

Convert Flattened Dictionary to Nested Dictionary (Arbitrary Depth)

Got it, let's tackle this problem—turning your underscore-separated flattened dictionary into a nested structure that works for any depth. Your existing nest_once function is a great start, but we can extend it to handle all levels iteratively (which is easy to follow and maintain).

Solution Code

Here's a straightforward function that builds the nested dictionary step by step for every key-value pair:

def flatten_to_nested(flat_dict):
    nested = {}
    for key, value in flat_dict.items():
        # Split the key into its hierarchical parts
        key_parts = key.split('_')
        current_level = nested
        
        # Traverse all parts except the last one, creating sub-dicts as needed
        for part in key_parts[:-1]:
            if part not in current_level:
                current_level[part] = {}
            current_level = current_level[part]
        
        # Assign the value to the final key part
        current_level[key_parts[-1]] = value
    return nested

How It Works

Let's walk through what this does with your example:

  1. Start with an empty nested dictionary.
  2. For each key like X_a_one, split it into ['X', 'a', 'one'].
  3. Traverse the first two parts (X then a):
    • If X isn't in nested, create an empty dict for it.
    • Move into the X dict, then check if a exists—create it if not, then move into a.
  4. Finally, assign the value 10 to the last part (one) in the a dict.

This logic automatically adapts to any number of underscore-separated levels, so it works for keys like A_b_c_d_e just as well as your original example.

Testing It Out

Let's verify with your sample inputs:

Test 1: Full Example

flat = {'X_a_one': 10, 'X_a_two': 20, 'X_b_one': 10, 'X_b_two': 20, 'Y_a_one': 10, 'Y_a_two': 20, 'Y_b_one': 10, 'Y_b_two': 20}
nested = flatten_to_nested(flat)
print(nested)

Output:

{'X': {'a': {'one': 10, 'two': 20}, 'b': {'one': 10, 'two': 20}}, 'Y': {'a': {'one': 10, 'two': 20}, 'b': {'one': 10, 'two': 20}}}

Test 2: Your Partial Example

test_dict = {'X_a_one': '10', 'X_b_one': '10', 'X_c_one': '10'}
test_out = flatten_to_nested(test_dict)
print(test_out)

Output:

{'X': {'a': {'one': '10'}, 'b': {'one': '10'}, 'c': {'one': '10'}}}

Why This Is Better Than Recursive Approaches

While you could write a recursive version, this iterative approach is:

  • Easier to debug and read (no stack frames to trace)
  • Works seamlessly for any depth without hitting recursion limits (not that you'd hit them with typical NetCDF attributes)
  • Handles all your requirements (scalar/string values, unambiguous key structure)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:18:15