字典是數(shù)據(jù)結(jié)構(gòu),其中包含關(guān)鍵值組合。 這些被廣泛用于代替JSON - JavaScript Object Notation。 字典用于API(應(yīng)用程序編程接口)編程。 字典將一組對象映射到另一組對象。 字典是可變的; 這意味著它們可以根據(jù)需要根據(jù)需要進(jìn)行更改。
如何在Python中實(shí)現(xiàn)字典?
下面的程序展示了從Python創(chuàng)建到Python中字典的基本實(shí)現(xiàn)。
# 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)
執(zhí)行上面示例代碼,得到以下結(jié)果 -
注 - 在Python中執(zhí)行字典有缺陷。
缺陷
字典不支持字符串,元組和列表等序列數(shù)據(jù)類型的序列操作。 這些屬于內(nèi)置的映射類型。