如何将扁平化字典转换为任意深度的嵌套字典?
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:
- Start with an empty
nesteddictionary. - For each key like
X_a_one, split it into['X', 'a', 'one']. - Traverse the first two parts (
Xthena):- If
Xisn't innested, create an empty dict for it. - Move into the
Xdict, then check ifaexists—create it if not, then move intoa.
- If
- Finally, assign the value
10to the last part (one) in theadict.
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

