字典實現

字典是數據結構,其中包含關鍵值組合。 這些被廣泛用於代替JSON - JavaScript Object Notation。 字典用於API(應用程式編程介面)編程。 字典將一組對象映射到另一組對象。 字典是可變的; 這意味著它們可以根據需要根據需要進行更改。

如何在Python中實現字典?

下麵的程式展示了從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)

執行上面示例代碼,得到以下結果 -

注 - 在Python中執行字典有缺陷。

缺陷
字典不支持字串,元組和列表等序列數據類型的序列操作。 這些屬於內置的映射類型。


上一篇: 迭代器設計模式 下一篇: 列表數據結構