網站首頁 編程語言 正文
Python字典設置默認值
我們都知道,在 Python 的字典里邊,如果 key 不存在的話,通過 key 去取值是會報錯的。
>>> aa = {'a':1, 'b':2}
>>> aa['c']
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
KeyError: 'c'
如果我們在取不到值的時候不報錯而是給定一個默認值的話就友好多了。
初始化的時候設定默認值(defaultdict 或 dict.fromkeys)
>>> from collections import defaultdict
>>> aa = defaultdict(int)
>>> aa['a'] = 1
>>> aa['b'] = 2
>>> aa
defaultdict(<class 'int'>, {'a': 1, 'b': 2})
>>> aa['c']
0
>>> aa
defaultdict(<class 'int'>, {'a': 1, 'b': 2, 'c': 0})
>>> aa = dict.fromkeys('abc', 0)
>>> aa
{'a': 0, 'b': 0, 'c': 0}
defaultdict(default_factory) 中的 default_factory 也可以傳入自定義的匿名函數之類的喲。?
>>> aa = defaultdict(lambda : 1)
>>> aa['a']
1
獲取值之前的時候設定默認值(setdefault(key, default))?
這里有個比較特殊的點:只要對應的 key 已經被設定了值之后,那么對相同 key 再次設置默認值就沒用了。
因此,如果你在循環里邊給一個 key 重復設定默認值的話,那么也只會第一次設置的生效。
>>> aa = {'a':1, 'b':2}
>>> aa
{'a': 1, 'b': 2}
>>> aa.get('c')
>>> aa.setdefault('c', 'hello')
'hello'
>>> aa.get('c')
'hello'
>>> aa
{'a': 1, 'b': 2, 'c': 'hello'}
>>> aa.setdefault('c', 'world')
'hello'
>>> aa.get('c')
'hello'
獲取值的時候設定默認值(dict.get(key, default))
>>> aa = {'a':1, 'b':2}
>>> aa
{'a': 1, 'b': 2}
>>> aa['c']
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
KeyError: 'c'
>>> aa.get('c')
>>> aa
{'a': 1, 'b': 2}
>>> aa.get('c', 'hello')
'hello'
>>> aa.get('b')
2
python創建帶默認值的字典
防止keyerror創建帶默認值的字典
from collections import defaultdict
data = collections.defaultdict(lambda :[])
總結
原文鏈接:https://blog.csdn.net/TomorrowAndTuture/article/details/113121157
- 上一篇:沒有了
- 下一篇:沒有了
相關推薦
- 2023-07-26 ndoe中express框架的基本使用,接收get、post請求,以及處理回調地獄的優雅解決方法
- 2022-04-01 containerd常用命令
- 2022-04-14 Python實現用戶注冊登錄程序_python
- 2022-10-31 Rust?實現?async/await的詳細代碼_相關技巧
- 2022-08-03 基于PyQt5完成pdf轉word功能_python
- 2024-03-03 ElementUi tab組件切換導致echarts寬度變窄問題
- 2022-12-04 詳解Go?依賴管理?go?mod?tidy_Golang
- 2022-04-12 Top-level statements must precede namespace and ty
- 欄目分類
-
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支