Table of Contents
Preface
OrderedDict
1) popitem(last=True):
2) move_to_end(key, last=True):
UserDict
1) data
DefaultDict
1) __missing__(key):
2)default_factory
本文小结
Home Backend Development Python Tutorial Python Programming: Detailed explanation of built-in dictionary (dict) subclasses and applications (all in one place)

Python Programming: Detailed explanation of built-in dictionary (dict) subclasses and applications (all in one place)

Apr 12, 2023 am 09:04 AM
python programming dictionary

Preface

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.

OrderedDict

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]):
Copy after login

or

from collections import OrderedDict
ordDict = OrderedDict([items]):
Copy after login

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.

1) popitem(last=True):

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.

2) move_to_end(key, last=True):

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:

Python Programming: Detailed explanation of built-in dictionary (dict) subclasses and applications (all in one place)

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:

Python Programming: Detailed explanation of built-in dictionary (dict) subclasses and applications (all in one place)

The running result is as follows:

删除前的OrderedDict:
x X
y Y
z Z
插入后的OrderedDict:
y Y
z Z
x X
Copy after login

UserDict

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])
Copy after login
Copy after login

or

import collections
userDict = collections.UserDict([initialdata])
Copy after login
Copy after login

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:

1) data

A real dictionary used to store the contents of the UserDict class. An example is as follows:

Python Programming: Detailed explanation of built-in dictionary (dict) subclasses and applications (all in one place)

The output is as follows:

{'name': 'Kevin Cui', 'age': 24}
Copy after login

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:

Python Programming: Detailed explanation of built-in dictionary (dict) subclasses and applications (all in one place)

#The running output is as follows:

{'x': 10, 'y': 20}
Copy after login

Of course, you can also implement other related custom operations yourself .

DefaultDict

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, /[,…])
Copy after login

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:

1) __missing__(key):

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.

2)default_factory

DefaultDict对象支持default_factory实例变量。该属性由__missing__()方法使用。如果存在,则从构造函数的第一个参数开始初始化;如果不存在,则初始化为None。

Python Programming: Detailed explanation of built-in dictionary (dict) subclasses and applications (all in one place)

运行程序输出结果为:

[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

Copy after login

在上述代码中,我们使用列表类型作为default_factory,更易于将包含键值序列对的列表组成字典。当第一次遇到每个键时,它还不在映射中,因此使用default_factory函数自动创建一个条目,该函数返回一个空列表。然后list.append()操作将值连接到新列表。当再次遇到键时,查找正常进行(返回该键的列表),然后list.append()操作将另一个值添加到列表中。这种技术比使用dict.setdefault()的等效技术要简单得多。

我们再看一个示例:

Python Programming: Detailed explanation of built-in dictionary (dict) subclasses and applications (all in one place)

输出结果如下:

[('a', 2), ('c', 1), ('g', 2), ('h', 1), ('i', 1), ('j', 1), ('n', 2)]
Copy after login

在上面代码中,我们将default_factory设置为int。这使得defaultdict用于计数(就像其他语言中的bag或multiset)。

当第一次遇到某个字母时,它就在映射中是不存在的,因此default_factory函数调用int()来提供一个默认的0计数。然后递增操作为每个字母建立计数。

提示:这里传递的int()函数默认返回的是整数0。若想返回任意值,可以自定义个一个基于lambda的常量函数。示例代码如下:

Python Programming: Detailed explanation of built-in dictionary (dict) subclasses and applications (all in one place)

一言以蔽之:使用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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles