Python 程式修改字典中等於 K 的值
字典是 Python 中可用的資料結構之一,用於以鍵值對的形式儲存任何資料型別的資料。它用 {} 花括號表示。字典中的鍵是唯一的,字典中的值可以重複。鍵值對之間使用分號“:”分隔。它是可變的,即一旦建立了字典,我們就可以修改資料。
字典用途廣泛,在 Python 中被廣泛用於對映和儲存資料,在需要根據鍵快速訪問值時非常有用。
字典是無序的,可以巢狀。它允許使用者使用相應的鍵訪問值。有很多函式支援字典來修改和訪問特定鍵的值。
在本文中,我們將使用各種技術來修改字典中等於 K 的值。讓我們逐一瞭解。
使用“for”迴圈
我們都知道,for 迴圈用於迭代定義的資料結構中的所有值。在這裡,我們使用 for 迴圈迭代字典的項,並在值等於 K 時更新值。
示例
在此示例中,我們嘗試使用 for 迴圈迭代字典項,並檢查是否有任何值等於 K 的值,然後使用新值更新鍵。
def change_value_if_equals_K(dictionary, K, new_value):
for key, value in dictionary.items():
if value == K:
dictionary[key] = new_value
my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
print("The dictionary before update:",my_dict)
K = 2
new_value = 5
change_value_if_equals_K(my_dict, K, new_value)
print("The updated dictionary:",my_dict)
輸出
The dictionary before update: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
The updated dictionary: {'a': 1, 'b': 5, 'c': 3, 'd': 4}
使用字典推導式
字典推導式是一種簡單易用的機制,可以在瞬間對現有字典項執行過濾、對映和條件邏輯,從而建立新的字典。
示例
在這裡,我們透過傳遞條件邏輯來建立一個新字典,以檢查字典的任何值是否等於 K=2,然後使用新定義的值 5 更新鍵。
def change_value_if_equals_K(dictionary, K, new_value):
new_dict = {key: new_value if value == K else value for key, value in dictionary.items()}
return new_dict
my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
print("The dictionary before update:",my_dict)
K = 2
new_value = 5
updated_dict = change_value_if_equals_K(my_dict, K, new_value)
print("The updated dictionary:",my_dict)
輸出
The dictionary before update: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
The updated dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
使用 map() 函式
Python 中的 map() 函式將給定函式應用於可迭代物件的每個元素,並返回結果的迭代器。
雖然 map() 通常與函式一起使用,但它也可以與 lambda 函式一起使用,以在字典的值等於特定 K 值時更改該值。
示例
在此示例中,我們使用字典推導式來檢查是否有任何字典值等於 K=2,如果匹配則將其替換為新值。然後,map() 函式與 lambda 函式一起使用,形式為 lambda item: (item[0], new_value) if item[1] == K else item,以迭代字典的項。lambda 函式檢查值 (item[1]) 是否等於 K。如果等於,則返回一個包含鍵 (item[0]) 和新值 (new_value) 的元組。否則,它返回原始的鍵值對 (item)。
def change_dict_value(dictionary, K, new_value):
return {key: new_value if value == K else value for key, value in dictionary.items()}
my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 2}
print("The dictionary before update:",my_dict)
K = 2
new_value = '5'
new_dict = dict(map(lambda item: (item[0], new_value) if item[1] == K else item, my_dict.items()))
print("The updated dictionary:",new_dict)
輸出
The dictionary before update: {'a': 1, 'b': 2, 'c': 3, 'd': 2}
The updated dictionary: {'a': 1, 'b': '5', 'c': 3, 'd': '5'}
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP