Python 設計模式 - 字典



字典是資料結構,包括鍵值組合。它們廣泛用於替代 JSON(JavaScript 物件表示法)。字典用於 API(應用程式程式設計介面)程式設計。字典將一組物件對映到另一組物件。字典是可變的,這意味著可以根據需要隨時更改它們。

如何在 Python 中實現字典?

以下程式展示了在 Python 中實現字典的基本過程,從建立到實現。

# Create a new dictionary
d = dict() # or d = {}

# Add a key - value pairs to dictionary
d['xyz'] = 123
d['abc'] = 345

# print the whole dictionary
print(d)

# print only the keys
print(d.keys())

# print only values
print(d.values())

# iterate over dictionary
for i in d :
   print("%s %d" %(i, d[i]))
	
# another method of iteration
for index, value in enumerate(d):
   print (index, value , d[value])

# check if key exist 23. Python Data Structure –print('xyz' in d)

# delete the key-value pair
del d['xyz']

# check again
print("xyz" in d)

輸出

上述程式生成以下輸出 −

Dictionaries

注意 −在 Python 中實現字典存在缺點。

缺點

字典不支援諸如字串、元組和列表一類的序列資料型別的序列操作。這些屬於內建對映型別。

廣告