Python Design Patterns 简明教程

Python Design Patterns - Dictionaries

字典是包含键值组合的数据结构。这些已广泛用于 JSON - JavaScript 对象表示法。字典用于 API(应用程序编程接口)编程。字典将一组对象映射到另一组对象。字典是可变的;这意味着可以根据需要随时更改它们。

Dictionaries are the data structures, which include a key value combination. These are widely used in place of JSON – JavaScript Object Notation. Dictionaries are used for API (Application Programming Interface) programming. A dictionary maps a set of objects to another set of objects. Dictionaries are mutable; this means they can be changed as and when needed based on the requirements.

How to implement dictionaries in Python?

以下程序展示了 Python 中字典的基本实现,从创建到实现。

The following program shows the basic implementation of dictionaries in Python starting from its creation to its implementation.

# 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)

Output

上述程序生成以下输出 −

The above program generates the following output −

dictionaries

*注意 - * Python 中字典的实现存在缺点。

*Note −*There are drawbacks related to the implementation of dictionaries in Python.

Drawback

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

Dictionaries do not support the sequence operation of the sequence data types like strings, tuples and lists. These belong to the built-in mapping type.