字典实现

字典是数据结构,其中包含关键值组合。 这些被广泛用于代替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中执行字典有缺陷。

缺陷
字典不支持字符串,元组和列表等序列数据类型的序列操作。 这些属于内置的映射类型。


上一篇:迭代器设计模式

下一篇:列表数据结构

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程