如何为值为HashMap的嵌套HashMap添加函数类型注解?
嵌套HashMap的类型注解写法
根据你给出的嵌套HashMap结构,不同编程语言的类型注解写法略有不同,以下是常见场景的实现:
1. Java 语言
如果你的嵌套结构是固定两层(外层HashMap的value是内层HashMap,内层value为字符串),直接明确嵌套层级的类型即可:
import java.util.HashMap; public class NestedHashMapExample { // 定义获取数据的函数,参数为两层嵌套的HashMap public String getNestedValue(HashMap<String, HashMap<String, String>> nestedMap, String outerKey, String innerKey) { HashMap<String, String> innerMap = nestedMap.get(outerKey); return innerMap != null ? innerMap.get(innerKey) : null; } public static void main(String[] args) { HashMap<String, HashMap<String, String>> data = new HashMap<>(); HashMap<String, String> inner = new HashMap<>(); inner.put("bar", "baz"); data.put("foo", inner); NestedHashMapExample example = new NestedHashMapExample(); String value = example.getNestedValue(data, "foo", "bar"); System.out.println(value); // 输出 "baz" } }
如果是任意深度的嵌套HashMap(value可以是字符串或另一个HashMap),可以用泛型结合Object处理:
public Object getDeepValue(HashMap<String, Object> nestedMap, String... keys) { Object current = nestedMap; for (String key : keys) { if (current instanceof HashMap) { current = ((HashMap<String, Object>) current).get(key); } else { return null; // 路径不存在或类型不匹配 } } return current; }
2. Python 语言
Python 3.9+ 可以通过标准库typing模块或内置泛型标注嵌套字典:
from typing import Dict, Optional def get_nested_value(nested_map: Dict[str, Dict[str, str]], outer_key: str, inner_key: str) -> Optional[str]: inner_map = nested_map.get(outer_key) return inner_map.get(inner_key) if inner_map else None # 测试 data = { "foo": { "bar": "baz" } } print(get_nested_value(data, "foo", "bar")) # 输出 "baz"
如果是任意深度的嵌套,可借助Union定义递归类型:
from typing import Dict, Union, Optional NestedDict = Dict[str, Union[str, 'NestedDict']] def get_deep_value(nested_map: NestedDict, *keys) -> Optional[Union[str, NestedDict]]: current = nested_map for key in keys: if isinstance(current, dict) and key in current: current = current[key] else: return None return current
内容的提问来源于stack exchange,提问作者Misery
相关产品推荐
相关产品推荐

