摘要:dict.get(key[, default])key:要查找的键default:可选参数,键不存在时返回的默认值(默认为None)返回:键对应的值,或默认值# 创建字典person = {"name": "Alice", "age": 25, "city":
get是Python字典对象的方法,用于安全地获取字典中的值。它提供了比直接索引访问更安全的替代方案,避免KeyError异常。
dict.get(key[, default])key:要查找的键default:可选参数,键不存在时返回的默认值(默认为None)返回:键对应的值,或默认值# 创建字典person = {"name": "Alice", "age": 25, "city": "New York"}# 获取存在的键print(person.get("name")) # "Alice"print(person.get("age")) # 25# 获取不存在的键print(person.get("gender")) # None(没有默认值)print(person.get("gender", "unknown")) # "unknown"(有默认值)person = {"name": "Alice"}# 直接访问(可能抛出KeyError)try:print(person["gender"]) # KeyErrorexcept KeyError as e:print(f"错误: {e}")# 使用get(安全)print(person.get("gender")) # Noneprint(person.get("gender", "N/A")) # "N/A"# 多层嵌套字典的安全访问company = {"name": "Tech Corp","employees": {"Alice": {"age": 25, "position": "Engineer"},"Bob": {"age": 30, "position": "Manager"}}}# 安全获取嵌套值alice_age = company.get("employees", {}).get("Alice", {}).get("age", "Unknown")bob_age = company.get("employees", {}).get("Bob", {}).get("age", "Unknown")charlie_age = company.get("employees", {}).get("Charlie", {}).get("age", "Unknown")print(f"Alice年龄: {alice_age}") # 25print(f"Bob年龄: {bob_age}") # 30print(f"Charlie年龄: {charlie_age}") # Unknowndata = {"a": 1}# get - 只获取,不修改字典value = data.get("b", 0)print(value) # 0print(data) # {"a": 1}(未改变)# setdefault - 获取并设置默认值value = data.setdefault("b", 0)print(value) # 0print(data) # {"a": 1, "b": 0}(已修改)# 使用get提供默认值的字典转换original = {"a": 1, "b": 2, "c": 3}keys_to_extract = ["a", "c", "d"] # d不存在result = {k: original.get(k, 0) for k in keys_to_extract}print(result) # {'a': 1, 'c': 3, 'd': 0}def get_config_value(config, key, default=None):"""安全获取配置值,支持类型转换"""value = config.get(key, default)# 如果默认值不是None,尝试类型转换if default is not None and value is not None:try:return type(default)(value)except (ValueError, TypeError):return defaultreturn value# 使用示例config = {"timeout": "30", "retries": "3", "debug": "true"}timeout = get_config_value(config, "timeout", 10) # 30 (int)retries = get_config_value(config, "retries", 5) # 3 (int)debug = get_config_value(config, "debug", False) # True (bool)missing = get_config_value(config, "host", "localhost") # localhostdef count_items(items):"""统计项目出现次数"""counts = {}for item in items:counts[item] = counts.get(item, 0) + 1return counts# 使用示例words = ["apple", "banana", "apple", "orange", "banana", "apple"]word_counts = count_items(words)print(word_counts) # {'apple': 3, 'banana': 2, 'orange': 1}def safe_api_response(response, *keys, default=None):"""安全地获取嵌套API响应数据"""current = responsefor key in keys:if isinstance(current, dict):current = current.get(key, {})else:return defaultreturn current if current != {} else default# 使用示例api_response = {"data": {"user": {"profile": {"name": "Alice","age": 25}}}}name = safe_api_response(api_response, "data", "user", "profile", "name", default="Unknown")email = safe_api_response(api_response, "data", "user", "profile", "email", default="no-email")print(f"Name: {name}") # Aliceprint(f"Email: {email}") # no-emailimport timeitdata = {str(i): i for i in range(1000)}def test_get:return data.get("missing", None)def test_try_except:try:return data["missing"]except KeyError:return Noneprint("get方法:", timeit.timeit(test_get, number=100000))print("异常处理:", timeit.timeit(test_try_except, number=100000))# get通常比异常处理更快# 需要多次访问同一个键时data = {"a": 1, "b": 2, "c": 3}# 不推荐:多次调用getif data.get("a") and data.get("b"):result = data.get("a") + data.get("b")# 推荐:一次性获取a = data.get("a")b = data.get("b")if a is not None and b is not None:result = a + b不会。get是只读操作,不会修改原始字典:
data = {"a": 1}value = data.get("b", 2)print(data) # {"a": 1}(未改变)data = {"a": 1}# 两者在功能上等价val1 = data.get("b") # Noneval2 = data.get("b", None) # None# 但明确传递None更清晰data = {"a": None, "b": 2}# 无法直接区分print(data.get("a")) # None(值就是None)print(data.get("c")) # None(键不存在)# 解决方法:使用in检查或get两次if "a" in data:print("键存在,值可能是None")不可以。get是字典特有的方法:
lst = [1, 2, 3]try:lst.get(0) # AttributeErrorexcept AttributeError as e:print(f"错误: {e}")def deep_get(dictionary, *keys, default=None):"""深度安全获取嵌套字典值"""current = dictionaryfor key in keys:if isinstance(current, dict):current = current.get(key, {})else:return defaultreturn current if current != {} else default# 使用示例data = {"a": {"b": {"c": 1}}}print(deep_get(data, "a", "b", "c")) # 1print(deep_get(data, "a", "x", "c")) # Noneprint(deep_get(data, "a", "b", "c", "d")) # None# 使用or提供默认值(注意:0、""、False等也会触发)data = {"a": 0, "b": "", "c": False}value_a = data.get("a") or "default" # "default"(0被视为False)value_b = data.get("b") or "default" # "default"(空字符串被视为False)value_c = data.get("c") or "default" # "default"(False被视为False)value_d = data.get("d") or "default" # "default"(None被视为False)# 正确的做法:明确检查Nonevalue_a = data.get("a") if data.get("a") is not None else "default"def get_with_factory(dictionary, key, default_factory=None):"""使用工厂函数生成默认值"""if key in dictionary:return dictionary[key]elif default_factory is not None:return default_factoryelse:return None# 使用示例data = {"count": 5}new_count = get_with_factory(data, "count", lambda: 0) # 5missing_count = get_with_factory(data, "total", lambda: 0) # 0(工厂生成)empty_list = get_with_factory(data, "items", list) # (list工厂)# 健壮的配置读取函数def read_config(config_dict, key, expected_type=str, default=None):"""安全读取配置并验证类型"""value = config_dict.get(key, default)# 类型检查if value is not None and not isinstance(value, expected_type):try:value = expected_type(value)except (ValueError, TypeError):value = defaultreturn value# 使用示例config = {"port": "8080", "timeout": "30", "debug": "true"}port = read_config(config, "port", int, 80) # 8080 (int)timeout = read_config(config, "timeout", int, 10) # 30 (int)debug = read_config(config, "debug", bool, False) # True (bool)host = read_config(config, "host", str, "localhost") # localhostget方法是Python字典操作中最重要的安全机制之一,合理使用可以显著提高代码的健壮性和可读性。
来源:琢磨先生起飞吧