
- Python 基礎
- Python - 首頁
- Python - 概述
- Python - 歷史
- Python - 特性
- Python vs C++
- Python - Hello World 程式
- Python - 應用領域
- Python - 直譯器
- Python - 環境搭建
- Python - 虛擬環境
- Python - 基本語法
- Python - 變數
- Python - 資料型別
- Python - 型別轉換
- Python - Unicode 系統
- Python - 字面量
- Python - 運算子
- Python - 算術運算子
- Python - 比較運算子
- Python - 賦值運算子
- Python - 邏輯運算子
- Python - 位運算子
- Python - 成員運算子
- Python - 身份運算子
- Python - 運算子優先順序
- Python - 註釋
- Python - 使用者輸入
- Python - 數字
- Python - 布林值
- Python 控制語句
- Python - 控制流
- Python - 決策
- Python - if 語句
- Python - if else
- Python - 巢狀 if
- Python - Match-Case 語句
- Python - 迴圈
- Python - for 迴圈
- Python - for-else 迴圈
- Python - while 迴圈
- Python - break 語句
- Python - continue 語句
- Python - pass 語句
- Python - 巢狀迴圈
- Python 函式與模組
- Python - 函式
- Python - 預設引數
- Python - 關鍵字引數
- Python - 僅限關鍵字引數
- Python - 位置引數
- Python - 僅限位置引數
- Python - 可變引數
- Python - 變數作用域
- Python - 函式註解
- Python - 模組
- Python - 內建函式
- Python 字串
- Python - 字串
- Python - 字串切片
- Python - 修改字串
- Python - 字串連線
- Python - 字串格式化
- Python - 跳脫字元
- Python - 字串方法
- Python - 字串練習
- Python 列表
- Python - 列表
- Python - 訪問列表項
- Python - 修改列表項
- Python - 新增列表項
- Python - 刪除列表項
- Python - 迴圈遍歷列表
- Python - 列表推導式
- Python - 排序列表
- Python - 複製列表
- Python - 合併列表
- Python - 列表方法
- Python - 列表練習
- Python 元組
- Python - 元組
- Python - 訪問元組項
- Python - 更新元組
- Python - 解包元組
- Python - 迴圈遍歷元組
- Python - 合併元組
- Python - 元組方法
- Python - 元組練習
- Python 集合
- Python - 集合
- Python - 訪問集合項
- Python - 新增集合項
- Python - 刪除集合項
- Python - 迴圈遍歷集合
- Python - 合併集合
- Python - 複製集合
- Python - 集合運算子
- Python - 集合方法
- Python - 集合練習
- Python 字典
- Python - 字典
- Python - 訪問字典項
- Python - 修改字典項
- Python - 新增字典項
- Python - 刪除字典項
- Python - 字典檢視物件
- Python - 迴圈遍歷字典
- Python - 複製字典
- Python - 巢狀字典
- Python - 字典方法
- Python - 字典練習
- Python 陣列
- Python - 陣列
- Python - 訪問陣列項
- Python - 新增陣列項
- Python - 刪除陣列項
- Python - 迴圈遍歷陣列
- Python - 複製陣列
- Python - 反轉陣列
- Python - 排序陣列
- Python - 合併陣列
- Python - 陣列方法
- Python - 陣列練習
- Python 檔案處理
- Python - 檔案處理
- Python - 寫入檔案
- Python - 讀取檔案
- Python - 重新命名和刪除檔案
- Python - 目錄
- Python - 檔案方法
- Python - OS 檔案/目錄方法
- Python - OS 路徑方法
- 面向物件程式設計
- Python - OOPs 概念
- Python - 類與物件
- Python - 類屬性
- Python - 類方法
- Python - 靜態方法
- Python - 建構函式
- Python - 訪問修飾符
- Python - 繼承
- Python - 多型
- Python - 方法重寫
- Python - 方法過載
- Python - 動態繫結
- Python - 動態型別
- Python - 抽象
- Python - 封裝
- Python - 介面
- Python - 包
- Python - 內部類
- Python - 匿名類和物件
- Python - 單例類
- Python - 包裝類
- Python - 列舉
- Python - 反射
- Python 錯誤與異常
- Python - 語法錯誤
- Python - 異常
- Python - try-except 塊
- Python - try-finally 塊
- Python - 丟擲異常
- Python - 異常鏈
- Python - 巢狀 try 塊
- Python - 使用者自定義異常
- Python - 日誌記錄
- Python - 斷言
- Python - 內建異常
- Python 多執行緒
- Python - 多執行緒
- Python - 執行緒生命週期
- Python - 建立執行緒
- Python - 啟動執行緒
- Python - 合併執行緒
- Python - 執行緒命名
- Python - 執行緒排程
- Python - 執行緒池
- Python - 主執行緒
- Python - 執行緒優先順序
- Python - 守護執行緒
- Python - 執行緒同步
- Python 同步
- Python - 執行緒間通訊
- Python - 執行緒死鎖
- Python - 中斷執行緒
- Python 網路程式設計
- Python - 網路程式設計
- Python - 套接字程式設計
- Python - URL 處理
- Python - 泛型
- Python 庫
- NumPy 教程
- Pandas 教程
- SciPy 教程
- Matplotlib 教程
- Django 教程
- OpenCV 教程
- Python 雜項
- Python - 日期與時間
- Python - 數學
- Python - 迭代器
- Python - 生成器
- Python - 閉包
- Python - 裝飾器
- Python - 遞迴
- Python - 正則表示式
- Python - PIP
- Python - 資料庫訪問
- Python - 弱引用
- Python - 序列化
- Python - 模板
- Python - 輸出格式化
- Python - 效能測量
- Python - 資料壓縮
- Python - CGI 程式設計
- Python - XML 處理
- Python - GUI 程式設計
- Python - 命令列引數
- Python - 文件字串
- Python - JSON
- Python - 傳送郵件
- Python - 更多擴充套件
- Python - 工具/實用程式
- Python - GUIs
- Python 高階概念
- Python - 抽象基類
- Python - 自定義異常
- Python - 高階函式
- Python - 物件內部
- Python - 記憶體管理
- Python - 元類
- Python - 使用元類進行超程式設計
- Python - 模擬和存根
- Python - 猴子補丁
- Python - 訊號處理
- Python - 型別提示
- Python - 自動化教程
- Python - Humanize 包
- Python - 上下文管理器
- Python - 協程
- Python - 描述符
- Python - 診斷和修復記憶體洩漏
- Python - 不可變資料結構
- Python 有用資源
- Python - 問答
- Python - 線上測驗
- Python - 快速指南
- Python - 參考
- Python - 速查表
- Python - 專案
- Python - 有用資源
- Python - 討論
- Python 編譯器
- NumPy 編譯器
- Matplotlib 編譯器
- SciPy 編譯器
Python - 新增字典項
新增字典項
在 Python 中新增字典項是指將新的鍵值對插入到現有的字典中。字典是可變的資料結構,用於儲存鍵值對的集合,其中每個鍵都與相應的值相關聯。
向字典新增項允許您根據需要在程式執行期間動態更新和擴充套件其內容。
我們可以使用多種方法在 Python 中新增字典項,例如:
- 使用方括號
- 使用 update() 方法
- 使用推導式
- 使用解包
- 使用並集運算子
- 使用 |= 運算子
- 使用 setdefault() 方法
- 使用 collections.defaultdict() 方法
使用方括號新增字典項
Python 中的方括號 **[]** 用於透過索引和切片操作訪問列表和字串等序列中的元素。此外,在使用字典時,方括號用於指定用於訪問或修改關聯值的鍵。
您可以透過在方括號中指定鍵併為其賦值來向字典新增項。如果鍵已存在於字典物件中,則其值將更新為 val。如果鍵不存在於字典中,則會新增新的鍵值對。
示例
在這個例子中,我們建立了一個名為“marks”的字典,其鍵代表姓名,相應的值為整數。然後,我們使用方括號表示法將新的鍵值對 'Kavta': 58 新增到字典中:
marks = {"Savita":67, "Imtiaz":88, "Laxman":91, "David":49} print ("Initial dictionary: ", marks) marks['Kavya'] = 58 print ("Dictionary after new addition: ", marks)
這將產生以下輸出:
Initial dictionary: {'Savita': 67, 'Imtiaz': 88, 'Laxman': 91, 'David': 49} Dictionary after new addition: {'Savita': 67, 'Imtiaz': 88, 'Laxman': 91, 'David': 49, 'Kavya': 58}
使用 update() 方法新增字典項
Python字典中的`update()`方法用於將另一個字典或鍵值對的可迭代物件的內容合併到當前字典中。它新增或更新鍵值對,確保用新值更新現有鍵,並將新鍵新增到字典中。
可以透過傳遞另一個字典或鍵值對的可迭代物件,使用`update()`方法向字典中新增多個項。
示例
在下面的例子中,我們使用`update()`方法向字典`marks`中新增多個新的鍵值對'Kavya': 58 和 'Mohan': 98 −
marks = {"Savita":67, "Imtiaz":88} print ("Initial dictionary: ", marks) marks.update({'Kavya': 58, 'Mohan': 98}) print ("Dictionary after new addition: ", marks)
我們將得到如下所示的輸出 −
Initial dictionary: {'Savita': 67, 'Imtiaz': 88} Dictionary after new addition: {'Savita': 67, 'Imtiaz': 88, 'Kavya': 58, 'Mohan': 98}
使用解包新增字典項
Python中的解包是指從集合(如列表、元組或字典)中提取單個元素,並將它們在一個語句中賦值給變數。這可以使用`*`運算子來對列表和元組等可迭代物件進行操作,並使用`**`運算子來對**字典**進行操作。
我們可以使用解包來新增字典項,方法是使用`**`解包運算子組合兩個或多個字典。
示例
在下面的例子中,我們初始化了兩個名為“marks”和“marks1”的字典,兩者都包含名稱及其對應的整數值。然後,我們透過使用字典解包合併“marks”和“marks1”來建立一個新的字典“newmarks” −
marks = {"Savita":67, "Imtiaz":88, "Laxman":91, "David":49} print ("marks dictionary before update: \n", marks) marks1 = {"Sharad": 51, "Mushtaq": 61, "Laxman": 89} newmarks = {**marks, **marks1} print ("marks dictionary after update: \n", newmarks)
以上程式碼的輸出如下 −
marks dictionary before update: {'Savita': 67, 'Imtiaz': 88, 'Laxman': 91, 'David': 49} marks dictionary after update: {'Savita': 67, 'Imtiaz': 88, 'Laxman': 89, 'David': 49, 'Sharad': 51, 'Mushtaq': 61}
使用並集運算子 (|) 新增字典項
Python中的並集運算子,用`|`符號表示,用於將兩個集合的元素組合成一個新集合,其中包含兩個集合中的所有唯一元素。它也可以在Python 3.9及更高版本中與字典一起使用,以合併兩個字典的內容。
我們可以使用並集運算子透過將兩個字典合併到一個新字典中來新增字典項,其中包括兩個字典中的所有鍵值對。
示例
在這個例子中,我們使用`|`運算子組合字典“marks”和“marks1”,如果鍵重複,“marks1”的值優先 −
marks = {"Savita":67, "Imtiaz":88, "Laxman":91, "David":49} print ("marks dictionary before update: \n", marks) marks1 = {"Sharad": 51, "Mushtaq": 61, "Laxman": 89} newmarks = marks | marks1 print ("marks dictionary after update: \n", newmarks)
以上程式碼的輸出如下所示 −
marks dictionary before update: {'Savita': 67, 'Imtiaz': 88, 'Laxman': 91, 'David': 49} marks dictionary after update: {'Savita': 67, 'Imtiaz': 88, 'Laxman': 89, 'David': 49, 'Sharad': 51, 'Mushtaq': 61}
使用`|=`運算子新增字典項
Python中的`|=`運算子是集合和字典的原地並集運算子。它使用來自右側集合或字典中的元素來更新左側的集合或字典。
我們可以使用`|=`運算子透過使用來自另一個字典的鍵值對更新現有字典來新增字典項。如果存在重疊的鍵,則來自右側字典的值將覆蓋左側字典中的值。
示例
在下面的例子中,我們使用`|=`運算子用來自“marks1”的鍵值對更新“marks”,其中來自“marks1”的值在鍵重複時優先 −
marks = {"Savita":67, "Imtiaz":88, "Laxman":91, "David":49} print ("marks dictionary before update: \n", marks) marks1 = {"Sharad": 51, "Mushtaq": 61, "Laxman": 89} marks |= marks1 print ("marks dictionary after update: \n", marks)
產生的輸出如下所示 −
marks dictionary before update: {'Savita': 67, 'Imtiaz': 88, 'Laxman': 91, 'David': 49} marks dictionary after update: {'Savita': 67, 'Imtiaz': 88, 'Laxman': 89, 'David': 49, 'Sharad': 51, 'Mushtaq': 61}
使用`setdefault()`方法新增字典項
Python中的`setdefault()`方法用於獲取字典中指定鍵的值。如果鍵不存在,它將插入具有指定預設值的鍵。
我們可以使用`setdefault()`方法透過指定鍵和預設值來新增字典項。
示例
在這個例子中,我們使用`setdefault()`向“student”字典新增鍵值對“major”: “Computer Science” −
# Initial dictionary student = {"name": "Alice", "age": 21} # Adding a new key-value pair major = student.setdefault("major", "Computer Science") print(student)
由於鍵“major”不存在,因此它將使用指定的預設值新增,如下面的輸出所示 −
{'name': 'Alice', 'age': 21, 'major': 'Computer Science'}
使用`collections.defaultdict()`方法新增字典項
Python中的`collections.defaultdict()`方法是內建“dict”類的子類,它建立具有預設值的字典,這些預設值用於尚未設定的鍵。它是Python標準庫中`collections`模組的一部分。
我們可以使用`collections.defaultdict()`方法透過指定一個預設工廠來新增字典項,該工廠確定尚未設定的鍵的預設值。首次訪問缺失的鍵時,將呼叫預設工廠來建立預設值,並將此值插入到字典中。
示例
在這個例子中,我們正在初始化具有不同預設工廠的`defaultdict`例項:`int`用於用0初始化缺失的鍵,`list`用於用空列表初始化缺失的鍵,以及自定義函式`default_value`用於用函式的返回值初始化缺失的鍵 −
from collections import defaultdict # Using int as the default factory to initialize missing keys with 0 d = defaultdict(int) # Incrementing the value for key 'a' d["a"] += 1 print(d) # Using list as the default factory to initialize missing keys with an empty list d = defaultdict(list) # Appending to the list for key 'b' d["b"].append(1) print(d) # Using a custom function as the default factory def default_value(): return "N/A" d = defaultdict(default_value) print(d["c"])
獲得的輸出如下 −
defaultdict(<class 'int'>, {'a': 1}) defaultdict(<class 'list'>, {'b': [1]}) N/A