如何通过指定列表作为键路径从嵌套字典中取值?
Access Nested Dictionary Values with Path Tuples/Lists
The cleanest way to achieve this is to subclass Python's built-in dict and override the __getitem__ (and optionally __setitem__) methods to handle tuple/list paths directly. Here's how to do it step by step:
Step 1: Create a Custom Nested Dictionary Class
This class extends dict and adds support for path-based key access while preserving all standard dictionary behavior:
class NestedDict(dict): def __getitem__(self, key): # Handle tuple/list paths if isinstance(key, (list, tuple)): current = self for part in key: current = current[part] return current # Fall back to normal dict behavior for single keys return super().__getitem__(key) def __setitem__(self, key, value): # Optional: Add support for setting values via paths if isinstance(key, (list, tuple)): current = self # Traverse all path segments except the last one for part in key[:-1]: # Auto-create nested NestedDict if the segment doesn't exist if part not in current: current[part] = NestedDict() current = current[part] # Set the final value current[key[-1]] = value else: super().__setitem__(key, value)
Step 2: Usage Examples
Now you can use tuple or list paths just like regular keys for both getting and setting values:
# Initialize your nested data my_dict = NestedDict({ "main": { "foo": {"xyz": 42}, "bar": {"abc": "Hello World!"} } }) # Get values with path tuples print(my_dict["main", "foo", "xyz"]) # Output: 42 print(my_dict["main", "bar", "abc"]) # Output: Hello World! # Get values with path lists (works too) print(my_dict[["main", "foo", "xyz"]]) # Output: 42 # Set values using paths (auto-creates nested structures if needed) my_dict["main", "new_section", "value"] = "New Entry" print(my_dict["main", "new_section", "value"]) # Output: New Entry
Alternative: Helper Function (No Subclassing)
If you don't want to subclass dict, use standalone functions to traverse paths in regular dictionaries:
def get_nested_value(data, path): current = data for segment in path: current = current[segment] return current def set_nested_value(data, path, value): current = data for segment in path[:-1]: if segment not in current: current[segment] = {} current = current[segment] current[path[-1]] = value # Usage with a regular dict my_regular_dict = { "main": {"foo": {"xyz": 42}} } print(get_nested_value(my_regular_dict, ["main", "foo", "xyz"])) # Output:42 set_nested_value(my_regular_dict, ["main", "bar"], "test") print(my_regular_dict["main"]["bar"]) # Output: test
Key Notes
- The subclass approach keeps all standard
dictfeatures (like.keys(),.items()) intact while adding path support. - Both methods raise
KeyErrorif any path segment doesn't exist, matching Python's normal nested dictionary behavior. - The
__setitem__override inNestedDictautomatically creates nested dictionaries, making it easy to build complex structures on the fly.
内容的提问来源于stack exchange,提问作者C1N14
相关产品推荐
相关产品推荐

