字典是数据结构,包括键值组合.这些被广泛用于代替JSON - JavaScript Object Notation.字典用于API(应用程序编程接口)编程.字典将一组对象映射到另一组对象.字典是可变的;这意味着它们可以根据需要在需要时进行更改.
如何在Python中实现字典?
以下程序显示了基本知识Python中字典的实现从创建到实现.
# Create a new dictionaryd = dict() # or d = {}# Add a key - value pairs to dictionaryd['xyz'] = 123d['abc'] = 345# print the whole dictionaryprint(d)# print only the keysprint(d.keys())# print only valuesprint(d.values())# iterate over dictionaryfor i in d : print("%s %d" %(i, d[i]))# another method of iterationfor 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 pairdel d['xyz']# check againprint("xyz" in d)
输出
上面的程序生成以下输出 :
注意; 在Python中实现字典有一些缺点.
缺点
字典不支持序列操作序列数据类型,如字符串,元组和列表.这些属于内置映射类型.