Python程式:向字典新增元素
Python 是一種高階通用程式語言,非常受歡迎。Python 用於各種尖端軟體開發專案,例如 Web 開發和機器學習應用程式。
在本文中,我們將學習向字典新增元素的各種方法。
你對Python中的字典有什麼理解?
Python 中的字典儲存鍵值對,這與其他只包含單個值作為元素的資料型別不同。它用於像對映一樣儲存資料值。字典包含鍵值對,使其更高效。
在字典中,每個鍵值對由冒號分隔;相反,每個鍵由逗號分隔。字典的鍵值可以重複,可以是任何型別,但鍵值必須是不同的,並且是不可變的資料型別,例如字串、整數和元組。
語法
Key:value
首先讓我們學習如何建立一個字典:
我們可以透過多種方式建立字典,例如函式式方法,你首先建立字典類,然後定義_init_函式。眾所周知,字典包含鍵值對,接下來我們將編寫一個函式來新增鍵值對,最後是主函式。
但這裡我們將建立一個簡單的字典。
示例
下面的示例演示瞭如何在 Python 中建立字典。
# Let's create a dictionary here
create_dictionary = {'Name': 'Devang', 'Age': 24, 'Quality': 'Hardworking'}
print(create_dictionary)
輸出
{'Name': 'Devang', 'Age': 24, 'Quality': 'Hardworking'}
到目前為止,我們已經弄清楚了基礎知識。現在讓我們將這些基礎知識應用於向字典中新增元素。有幾種方法可以做到這一點,但這裡我們將瞭解四種最簡單且最重要的方法。
使用 update() 方法
此方法用於從可迭代的鍵值對或不同字典物件的元素更新字典。此方法很合適,因為它在需要新增多個鍵值對時可以簡化任務。
語法
dict.update([other])
示例
在下面的程式中,建立了一個名為 dict 的字典,其中包含兩個鍵值對。然後程式打印出字典的初始版本。下一行向字典新增另一個鍵值對並更新它。之後,建立一個名為“dictionary_A”的新字典,其中包含另外兩個鍵值對,然後使用 .update() 方法將其新增到 dict 中,並在最後一步打印出來。
dict = {'1': 'An', '2': 'Apple a day'}
print( "First Dictionary is as following :", dict)
# for adding the key3 that is an another key
dict.update({'3': 'keeps doctor'})
print( "Updated version of Dictionary is as following : ", dict)
# for adding from dictionary_A (key4 and key5) to dict
dictionary_A = {'4': 'is', '5': 'away'}
dict.update(dictionary_A)
print(dict)
輸出
First Dictionary is as following : {'1': 'An', '2': 'Apple a day'}
Updated version of Dictionary is as following : {'1': 'An', '2': 'Apple a day', '3': 'keeps doctor'}
{'1': 'An', '2': 'Apple a day', '3': 'keeps doctor', '4': 'is', '5': 'away'}
使用 For 迴圈和 enumerate() 方法
Python 提供了一個內建函式,即enumerate()方法。它的作用是向可迭代物件新增計數器,並以列舉物件的形成返回。
演算法
首先建立一個元素列表,然後使用 enumerate() 方法迭代列表。接下來,使用索引作為每個值的鍵將每個元素新增到字典中。
示例
程式中建立了一個字典和一個列表。然後,for 迴圈遍歷第二個列表中的每個專案,並將其分配給第一個列表中的一個鍵,其對應的索引作為鍵值。print 語句打印出for迴圈修改後的第一個列表的最終版本。
firstlist = {"Apple": 1, "Boy": 2, "Cat": 3}
secondlist = ["first: 1", "second:2", "third:3"]
for i, val in enumerate(secondlist):
firstlist[i] = val
print(firstlist)
輸出
{'Apple': 1, 'Boy': 2, 'Cat': 3, 0 : 'first : 1', 1 : 'second : 2', 2 : 'third : 3'}
使用 Zip 方法
當使用容器或可迭代物件時,Python 中的 zip() 函式建立一個包含來自每個容器的對映值的單個迭代器物件。它用於對映多個容器的共享索引,以便單個實體可以訪問所有這些容器。可以使用現有的字典代替 dictionary{}。
示例
下面的程式正在建立一個包含三個鍵 (1, 2, 3) 和值 ("Ship", "for", "sale") 的字典,然後它打印出生成的字典。
dictionary = {}
keys_num = ['1', '2', '3']
values_first = ['Ship', 'for', 'sale']
for keys_num, value_first in zip(keys_num, values_first):
dictionary[keys_num] = value_first
print(dictionary)
輸出
{‘1’: ‘Ship’, ‘2’: ‘for’, ‘3’: ‘sale’}
使用“in”運算子和 If 語句
在這種方法中,我們使用了if語句,該語句檢查鍵是否已存在於字典中。如果鍵不存在,則將其新增到字典中;如果評估後發現鍵已存在,則輸出結果為鍵已存在於字典中。
示例
下面的程式正在建立一個名為“firstdictionary”的字典,其鍵為“apple”、“boy”和“cat”。然後它檢查鍵“dog”是否存在於firstdictionary中。如果不存在,則它將鍵值對 (“dog”: 4) 新增到字典中。否則,它會打印出一條訊息,說明該鍵已存在於字典中,並且其值不會被覆蓋。最後,它打印出 firstdictionary 的所有內容。
firstdictionary = {"apple": 1, "boy": 2, "cat": 3}
if "dog" not in firstdictionary:
firstdictionary["dog"] = "4"
else:
print("Key is already present in the dictionary : One. Hence value is not overwritten ")
print(firstdictionary)
輸出
{'apple': 1, 'boy': 2, 'cat': 3, 'dog': '4'}
示例
在這裡,我們使用示例建立了一個差異,如果鍵不存在則顯示case1,否則顯示case2。
firstdictionary = {"apple": 1, "boy": 2, "cat": 3, "dog": 4}
if "dog" not in firstdictionary:
firstdictionary["dog"] = "4"
else:
print("Key is already present in the dictionary : One. Hence value is not overwritten ")
print(firstdictionary)
輸出
Key is already present in the dictionary : One. Hence value is not overwritten {'apple': 1, 'boy': 2, 'cat': 3, 'dog': 4}
使用 ** 運算子
在這種方法中,我們可以使用 ** 運算子直接合並兩個字典,即舊字典和新字典的鍵值對。因此,** 運算子的作用是將鍵值對解包到新的字典物件中。
演算法
建立一個字典,然後建立另一個字典,我們想將其合併到原始字典中。然後在鍵值對前面應用 ** 運算子。
示例
還有一種 _setitem_ 方法可以向字典新增元素,但它是一種計算效率低下的方法,因此我們通常不使用此方法。
firstdictionary = {'apple': 1, 'boy': 2}
new_dictionary = {**firstdictionary, **{'cat': 3}}
print(firstdictionary)
print(new_dictionary)
輸出
{'apple': 1, 'boy': 2}
{'apple': 1, 'boy': 2, 'cat': 3}
結論
在本文中,我們解釋了五種不同的方法,這五種方法展示了五種不同的方法來完成相同的任務,即使用 Python 向字典新增元素。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP