Home > Article > Backend Development > Python Programming: Detailed explanation of built-in dictionary (dict) subclasses and applications (all in one place)
This article mainly introduces the application scenarios and usage examples of several built-in extension subclasses of the dictionary class (dict) in the Python collection module. It is also combined with the code so that you can master these in a "short and quick way" Subclasses directly related to dict - OrderedDict, defaultdict, userDict.
The ordered dictionary (OrderedDict) in the Python collection module is just like a normal dictionary, but has some extra features related to sorting operations. OrderedDict remembers the order in which keys were inserted. They become less important now because the built-in dict class gained the ability to remember insertion order (this new behavior was guaranteed in Python 3.7, so OrderedDict seems less important now). General format for creating an ordered dictionary:
import collections ordDict = collections.OrderedDict([items]):
or
from collections import OrderedDict ordDict = OrderedDict([items]):
This creates and returns an OrderedDict object that is an instance of the dict subclass, which has methods specifically for rearranging dictionary order. This article briefly introduces these methods.
The popitem() method of the ordered dictionary returns and deletes a (key, value) pair. If last is True, the corresponding key-value pair is returned in LIFO (last in, first out) mode; otherwise, it is returned in FIFO (first in, first out) order.
Move the existing key to either end of the ordered dictionary. If last is True (the default), the item is moved to the right; if last is False, it is moved to the beginning. A KeyError will be raised if the key does not exist.
Please see the code:
Suppose we delete and reinsert the same key into the OrderedDict. It will put this key at the end to maintain the insertion order of keys. An example is as follows:
The running result is as follows:
删除前的OrderedDict: x X y Y z Z 插入后的OrderedDict: y Y z Z x X
The UserDict class is used as a wrapper for Python’s built-in dictionary (dict) objects . The need for this class has been partially replaced by the ability to subclass directly from dict; however, this class is easier to use because the underlying dictionary can be accessed as an attribute. Use UserDict when you want to create your own dictionary with some modified or new features. Its usage format is as follows:
import collections userDict = collections.UserDict([initialdata])
or
import collections userDict = collections.UserDict([initialdata])
This type of simulated dictionary has the content of its instance stored in a regular dictionary, which can be accessed through the data attribute of the UserDict instance. If initialdata is provided, the data content is initialized with this; note that the instance itself does not retain a separate (non-exclusive) reference to initialdata, allowing it to be used for other purposes.
In addition to supporting mapping methods and operations, UserDict instances provide the following attributes:
A real dictionary used to store the contents of the UserDict class. An example is as follows:
The output is as follows:
{'name': 'Kevin Cui', 'age': 24}
Suppose we want to define a custom dictionary object that supports addition operations (merging two dictionaries). When we add two instances of a custom dictionary, we expect to get a new dictionary containing all the elements in both dictionaries. Keep in mind that if you try to add to a regular dictionary in Python, you'll get a TypeError. Let us implement it with the help of UserDict:
#The running output is as follows:
{'x': 10, 'y': 20}
Of course, you can also implement other related custom operations yourself .
A common problem with the Dictionary class in Python is missing keys. When trying to access a key that does not exist in the dictionary, you will get a KeyError exception. So whenever you need to access an element in a dictionary, you have to handle this situation. Fortunately, Python provides the DefaultDict class. It is used to provide some default value for non-existent keys without raising KeyError.
DefaultDict is a subclass of the built-in dict class. It overrides a method and adds a writable instance variable. The rest of the functionality is the same as dict. The usage format is as follows:
import colloections defaultDict = collections.defaultdict(default_factory=None, /[,…])
The above code returns a new dictionary-like object DefaultDict, which is a subclass of the built-in dict class.
The first parameter provides the initial value for the default_factory attribute, which defaults to None. All remaining arguments are treated as if passed to the dict constructor, including keyword arguments. What needs to be understood is that if this parameter is provided, it must be callable.
In addition to supporting standard dict operations, the DefaultDict object also supports the following method attributes:
If the default_factory attribute is None, use the key as The parameter will raise a KeyError exception.
If default_factory is not None, calling it with no arguments provides a default value for the given key, which is inserted into the key's dictionary and returned.
DefaultDict对象支持default_factory实例变量。该属性由__missing__()方法使用。如果存在,则从构造函数的第一个参数开始初始化;如果不存在,则初始化为None。
运行程序输出结果为:
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
在上述代码中,我们使用列表类型作为default_factory,更易于将包含键值序列对的列表组成字典。当第一次遇到每个键时,它还不在映射中,因此使用default_factory函数自动创建一个条目,该函数返回一个空列表。然后list.append()操作将值连接到新列表。当再次遇到键时,查找正常进行(返回该键的列表),然后list.append()操作将另一个值添加到列表中。这种技术比使用dict.setdefault()的等效技术要简单得多。
我们再看一个示例:
输出结果如下:
[('a', 2), ('c', 1), ('g', 2), ('h', 1), ('i', 1), ('j', 1), ('n', 2)]
在上面代码中,我们将default_factory设置为int。这使得defaultdict用于计数(就像其他语言中的bag或multiset)。
当第一次遇到某个字母时,它就在映射中是不存在的,因此default_factory函数调用int()来提供一个默认的0计数。然后递增操作为每个字母建立计数。
提示:这里传递的int()函数默认返回的是整数0。若想返回任意值,可以自定义个一个基于lambda的常量函数。示例代码如下:
一言以蔽之:使用DefaultDict的好处就是可以避免KeyError异常,并进行一些可能的特定处理。
本文主要介绍了Python字典(dict)类相关的几个内置子类的应用。这些直接相关的子类分别是OrderedDict、defaultdict、userDict等内置子类。通过示例代码和关联描述,让你更轻松掌握它们的应用和基本规则。
The above is the detailed content of Python Programming: Detailed explanation of built-in dictionary (dict) subclasses and applications (all in one place). For more information, please follow other related articles on the PHP Chinese website!