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

关于用带方法的类实现Python嵌套字典构建的技术咨询

Got it, let's build that Dict class you're looking for! Here's a clean implementation that matches your requirements, with stack-based tracking to handle nested dictionary levels smoothly:

Implementation of the Dict Class
class Dict:
    def __init__(self):
        self.dict_test = {}
        # Use a stack to track which dictionary level we're actively working on
        self._level_stack = [self.dict_test]

    def level_up(self, key, value={}):
        """Add a key-value pair to the current level. If value is a dict, switch to it as the new active level."""
        current_dict = self._level_stack[-1]
        current_dict[key] = value
        # If we're adding a sub-dictionary, make it our new working level
        if isinstance(value, dict):
            self._level_stack.append(value)

    def level_down(self):
        """Move back to the parent dictionary level (does nothing if already at root)."""
        if len(self._level_stack) > 1:
            self._level_stack.pop()
        else:
            print("Warning: Already at the root level, can't go down further.")

    def current_add(self, key, value={}):
        """Add a key-value pair directly to the currently active dictionary level."""
        current_dict = self._level_stack[-1]
        current_dict[key] = value

Walkthrough with Your Example Operations

Let’s test this class exactly as you outlined:

  1. Initialization:

    d = Dict()
    print(d.dict_test)  # Output: {}
    

    We start with an empty root dictionary and a stack pointing to this root level.

  2. level_up adds a root-level key:

    d.level_up("Test1", "Value1")
    print(d.dict_test)  # Output: {"Test1": "Value1"}
    

    This adds Test1: Value1 to the root level. Since Value1 isn’t a dictionary, our active level stays at the root.

  3. current_add adds another root-level key:

    d.current_add("Test2")  # Uses default empty dict as value
    print(d.dict_test)  # Output: {"Test1": "Value1", "Test2": {}}
    

    This inserts Test2: {} directly into the current (root) level without changing our active position.

Testing Nested Functionality

To show how the class handles deeper levels:

# Create a sub-dict and switch to it
d.level_up("Test3", {})
# Add a key to the Test3 sub-dict
d.current_add("SubTest1", "SubValue1")
print(d.dict_test)  # Output: {"Test1": "Value1", "Test2": {}, "Test3": {"SubTest1": "SubValue1"}}

# Move back to the root level
d.level_down()
# Add another root-level key
d.current_add("Test4", "Value4")
print(d.dict_test)  # Output: {"Test1": "Value1", "Test2": {}, "Test3": {"SubTest1": "SubValue1"}, "Test4": "Value4"}

Quick Notes

  • The _level_stack is a private helper to track our current position in the nested structure—no need to interact with it directly.
  • I adjusted level_down to not require a key parameter (since moving up a level doesn’t need one), but if you specifically want to target a parent level via a key, we can tweak this easily.
  • If you want to avoid mutable default argument edge cases, we can change value={} to value=None and set value = {} inside the methods if needed.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:41:40