Python 字典 get() 方法:操作指南
bigegpt 2025-04-30 15:26 15 浏览
Python 中的字典 'get()' 方法可帮助安全地检索值,而无需担心 KeyError 异常。但它不仅仅是方括号表示法的更安全的替代方案,它还是一种编写更简洁、更易于维护的代码的工具。让我们看看如何有效地使用它。
基本用法和语法
下面是基本模式:
value = dictionary.get(key, default_value)
比较这些方法:
# Using square brackets - can raise KeyError
user = {"name": "John", "age": 30}
try:
email = user["email"]
except KeyError:
email = None
# Using get() - cleaner and more direct
user = {"name": "John", "age": 30}
email = user.get("email", None) # Returns None if key doesn't exist
高级用法
自定义默认值
# Dictionary of user preferences
preferences = {
"theme": "dark",
"notifications": True
}
# Get font size with a sensible default
font_size = preferences.get("font_size", 12)
# Get language with system default
import locale
system_language = locale.getdefaultlocale()[0]
language = preferences.get("language", system_language)
# Get refresh rate with calculated default
def calculate_default_refresh():
# Complex logic to determine optimal refresh rate
return 60
refresh_rate = preferences.get("refresh_rate", calculate_default_refresh())
实际应用
1. 配置管理
class AppConfig:
def __init__(self, config_dict):
self.debug = config_dict.get("debug", False)
self.host = config_dict.get("host", "localhost")
self.port = config_dict.get("port", 8080)
self.timeout = config_dict.get("timeout", 30)
self.retries = config_dict.get("retries", 3)
def as_dict(self):
return {
"debug": self.debug,
"host": self.host,
"port": self.port,
"timeout": self.timeout,
"retries": self.retries
}
# Usage
config = {
"host": "example.com",
"debug": True
}
app_config = AppConfig(config)
print(f"Server will run on {app_config.host}:{app_config.port}")
2. 使用默认值进行数据处理
def process_user_data(users):
processed_data = []
for user in users:
processed_user = {
"name": user.get("name", "Anonymous"),
"age": user.get("age", 0),
"status": user.get("status", "unknown").lower(),
"last_active": user.get("last_login", "never"),
"engagement_score": calculate_engagement(user)
}
processed_data.append(processed_user)
return processed_data
def calculate_engagement(user):
points = 0
points += 10 if user.get("profile_complete", False) else 0
points += min(user.get("posts_count", 0), 50)
points += min(user.get("comments_count", 0) * 0.5, 25)
return points
# Usage
users = [
{"name": "John", "posts_count": 20},
{"name": "Jane", "profile_complete": True, "comments_count": 30},
]
processed = process_user_data(users)
3. 嵌套词典导航
def safe_get_nested(dictionary, *keys, default=None):
"""Safely navigate nested dictionaries."""
current = dictionary
for key in keys:
if isinstance(current, dict):
current = current.get(key, default)
else:
return default
return current
# Example usage with deeply nested data
data = {
"user": {
"profile": {
"address": {
"city": "New York",
"country": "USA"
}
}
}
}
# Safe navigation
city = safe_get_nested(data, "user", "profile", "address", "city")
# Returns "New York"
# Non-existent path
postal = safe_get_nested(data, "user", "profile", "address", "postal_code", default="N/A")
# Returns "N/A"
4. 缓存实现
from time import time
class SimpleCache:
def __init__(self, default_timeout=300): # 5 minutes default
self._cache = {}
self.default_timeout = default_timeout
def get(self, key, default=None):
cache_item = self._cache.get(key, {})
if not cache_item:
return default
expiry = cache_item.get("expiry")
if expiry and time() > expiry:
del self._cache[key]
return default
return cache_item.get("value", default)
def set(self, key, value, timeout=None):
timeout = timeout or self.default_timeout
self._cache[key] = {
"value": value,
"expiry": time() + timeout
}
# Usage
cache = SimpleCache()
cache.set("user_123", {"name": "John", "age": 30})
user = cache.get("user_123", default={"name": "Unknown"})
高级技术
1. 使用 get() 进行字典推导
# Original data with missing values
data = [
{"id": 1, "name": "John"},
{"id": 2},
{"id": 3, "name": "Jane"}
]
# Create normalized dictionary
normalized = {
item["id"]: item.get("name", f"User_{item['id']}")
for item in data
}
# Result: {1: "John", 2: "User_2", 3: "Jane"}
2. 将 get() 与其他方法结合使用
def process_text_data(data_dict):
"""Process text data with various default transformations."""
processed = {
"title": data_dict.get("title", "").title(),
"description": data_dict.get("description", "").strip(),
"tags": [
tag.lower()
for tag in data_dict.get("tags", [])
],
"category": data_dict.get("category", "uncategorized").lower(),
"word_count": len(data_dict.get("content", "").split())
}
return processed
# Usage
article = {
"title": "python tips",
"description": " Helpful Python tips ",
"tags": ["Python", "Programming", "Tips"],
}
processed_article = process_text_data(article)
常见陷阱和解决方案
1. 可变默认值
# Problematic: List as default value
def get_tags(user_dict):
return user_dict.get("tags", []).append("default") # Returns None!
# Fixed version
def get_tags(user_dict):
tags = user_dict.get("tags", [])
tags.append("default")
return tags
2. 性能注意事项
# Inefficient: Calculating default value every time
def get_config(key):
return config_dict.get(key, expensive_calculation())
# Better: Calculate default only when needed
def get_config(key):
value = config_dict.get(key)
if value is None:
value = expensive_calculation()
return value
3. 类型安全
def get_int_value(dictionary, key, default=0):
"""Safely get an integer value from a dictionary."""
value = dictionary.get(key, default)
try:
return int(value)
except (TypeError, ValueError):
return default
# Usage
data = {"count": "123", "invalid": "abc"}
valid_count = get_int_value(data, "count") # Returns 123
invalid_count = get_int_value(data, "invalid") # Returns 0
missing_count = get_int_value(data, "missing") # Returns 0
'get()' 方法不仅仅是一个丢失键的安全网——它是一个编写更简洁、更易于维护的代码的工具。使用它来正常处理缺失值,提供合理的默认值,并使代码在应对意外输入时更加健壮。
相关推荐
- 当Frida来“敲”门(frida是什么)
-
0x1渗透测试瓶颈目前,碰到越来越多的大客户都会将核心资产业务集中在统一的APP上,或者对自己比较重要的APP,如自己的主业务,办公APP进行加壳,流量加密,投入了很多精力在移动端的防护上。而现在挖...
- 服务端性能测试实战3-性能测试脚本开发
-
前言在前面的两篇文章中,我们分别介绍了性能测试的理论知识以及性能测试计划制定,本篇文章将重点介绍性能测试脚本开发。脚本开发将分为两个阶段:阶段一:了解各个接口的入参、出参,使用Python代码模拟前端...
- Springboot整合Apache Ftpserver拓展功能及业务讲解(三)
-
今日分享每天分享技术实战干货,技术在于积累和收藏,希望可以帮助到您,同时也希望获得您的支持和关注。架构开源地址:https://gitee.com/msxyspringboot整合Ftpserver参...
- Linux和Windows下:Python Crypto模块安装方式区别
-
一、Linux环境下:fromCrypto.SignatureimportPKCS1_v1_5如果导包报错:ImportError:Nomodulenamed'Crypt...
- Python 3 加密简介(python des加密解密)
-
Python3的标准库中是没多少用来解决加密的,不过却有用于处理哈希的库。在这里我们会对其进行一个简单的介绍,但重点会放在两个第三方的软件包:PyCrypto和cryptography上,我...
- 怎样从零开始编译一个魔兽世界开源服务端Windows
-
第二章:编译和安装我是艾西,上期我们讲述到编译一个魔兽世界开源服务端环境准备,那么今天跟大家聊聊怎么编译和安装我们直接进入正题(上一章没有看到的小伙伴可以点我主页查看)编译服务端:在D盘新建一个文件夹...
- 附1-Conda部署安装及基本使用(conda安装教程)
-
Windows环境安装安装介质下载下载地址:https://www.anaconda.com/products/individual安装Anaconda安装时,选择自定义安装,选择自定义安装路径:配置...
- 如何配置全世界最小的 MySQL 服务器
-
配置全世界最小的MySQL服务器——如何在一块IntelEdison为控制板上安装一个MySQL服务器。介绍在我最近的一篇博文中,物联网,消息以及MySQL,我展示了如果Partic...
- 如何使用Github Action来自动化编译PolarDB-PG数据库
-
随着PolarDB在国产数据库领域荣膺桂冠并持续获得广泛认可,越来越多的学生和技术爱好者开始关注并涉足这款由阿里巴巴集团倾力打造且性能卓越的关系型云原生数据库。有很多同学想要上手尝试,却卡在了编译数据...
- 面向NDK开发者的Android 7.0变更(ndk android.mk)
-
订阅Google官方微信公众号:谷歌开发者。与谷歌一起创造未来!受Android平台其他改进的影响,为了方便加载本机代码,AndroidM和N中的动态链接器对编写整洁且跨平台兼容的本机...
- 信创改造--人大金仓(Kingbase)数据库安装、备份恢复的问题纪要
-
问题一:在安装KingbaseES时,安装用户对于安装路径需有“读”、“写”、“执行”的权限。在Linux系统中,需要以非root用户执行安装程序,且该用户要有标准的home目录,您可...
- OpenSSH 安全漏洞,修补操作一手掌握
-
1.漏洞概述近日,国家信息安全漏洞库(CNNVD)收到关于OpenSSH安全漏洞(CNNVD-202407-017、CVE-2024-6387)情况的报送。攻击者可以利用该漏洞在无需认证的情况下,通...
- Linux:lsof命令详解(linux lsof命令详解)
-
介绍欢迎来到这篇博客。在这篇博客中,我们将学习Unix/Linux系统上的lsof命令行工具。命令行工具是您使用CLI(命令行界面)而不是GUI(图形用户界面)运行的程序或工具。lsoflsof代表&...
- 幻隐说固态第一期:固态硬盘接口类别
-
前排声明所有信息来源于网络收集,如有错误请评论区指出更正。废话不多说,目前固态硬盘接口按速度由慢到快分有这几类:SATA、mSATA、SATAExpress、PCI-E、m.2、u.2。下面我们来...
- 新品轰炸 影驰SSD多款产品登Computex
-
分享泡泡网SSD固态硬盘频道6月6日台北电脑展作为全球第二、亚洲最大的3C/IT产业链专业展,吸引了众多IT厂商和全球各地媒体的热烈关注,全球存储新势力—影驰,也积极参与其中,为广大玩家朋友带来了...
- 一周热门
- 最近发表
-
- 当Frida来“敲”门(frida是什么)
- 服务端性能测试实战3-性能测试脚本开发
- Springboot整合Apache Ftpserver拓展功能及业务讲解(三)
- Linux和Windows下:Python Crypto模块安装方式区别
- Python 3 加密简介(python des加密解密)
- 怎样从零开始编译一个魔兽世界开源服务端Windows
- 附1-Conda部署安装及基本使用(conda安装教程)
- 如何配置全世界最小的 MySQL 服务器
- 如何使用Github Action来自动化编译PolarDB-PG数据库
- 面向NDK开发者的Android 7.0变更(ndk android.mk)
- 标签列表
-
- mybatiscollection (79)
- mqtt服务器 (88)
- keyerror (78)
- c#map (65)
- resize函数 (64)
- xftp6 (83)
- bt搜索 (75)
- c#var (76)
- mybatis大于等于 (64)
- xcode-select (66)
- mysql授权 (74)
- 下载测试 (70)
- linuxlink (65)
- pythonwget (67)
- androidinclude (65)
- libcrypto.so (74)
- logstashinput (65)
- hadoop端口 (65)
- vue阻止冒泡 (67)
- jquery跨域 (68)
- php写入文件 (73)
- kafkatools (66)
- mysql导出数据库 (66)
- jquery鼠标移入移出 (71)
- 取小数点后两位的函数 (73)