


Detailed explanation of the usage of items() series functions in Python
This article mainly introduces the usage of the dictionary items() series of functions in Python. It is a very practical function. Friends who need it can refer to it.
The example of this article describes the usage of the dictionary items() series of functions in Python. Usage, has a good reference value for Python programming. The specific analysis is as follows:
Let’s look at an example first:
import html # available only in Python 3.x def make_elements(name, value, **attrs): keyvals = [' %s="%s"' % item for item in attrs.items()] attr_str = ''.join(keyvals) element = '<{name}{attrs}>{value}</{name}>'.format( name = name, attrs = attr_str, value = html.escape(value)) return element make_elements('item', 'Albatross', size='large', quantity=6) make_elements('p', '<spam>')
The function of this program is very simple, it is to generate HTML tags. Note that the html module can only be used in Python 3 .x only exists.
At first I just noticed that the dictionary type variables of the keyvals that generate the tag attributeslist are very interesting. Two %s correspond to one item, so just After checking the relevant information, I found out a lot of things, which I will summarize here.
Note: For the versions used by all Python interpreters below, 2.x corresponds to 2.7.3, and 3.x corresponds to 3.4.1
In Python 2.x, items in the official documentation The method is explained as follows: generate a list of (key, value) pairs, like the following:
>>> d = {'size': 'large', 'quantity': 6} >>> d.items() [('quantity', 6), ('size', 'large')]
In the process of searching, I accidentally saw such a question on stackoverflow: What is the difference between dict.items() and dict.iteritems()? , the first answer roughly means this:
"At first, items() returned a list containing all the elements of dict like the above, but because this was too wasteful of memory, I later added ( Note: The group of functions iteritems(), iterkeys(), and itervalues() that began to appear in Python 2.2 are used to return an iterator to save memory, but in 3.x items() itself returns such an iterator. Therefore, the behavior of items() in 3.x is consistent with the behavior of iteritems() in 2.x, and the iteritems() function is abolished.”
But it’s more interesting. Yes, although this answer was accepted, the comments below pointed out that this statement is not accurate. The behavior of items() in 3.x is different from iteritems() in 2.x. It actually returns a " full sequence-protocol object", this object can reflect changes in dict. Later, another function viewitems() was added to Python 2.7 and this behavior in 3.x To be consistent
To confirm the claims in the comments, I did the following test, paying attention to the Python version used in the test:
Test 1 (Python 2.7.3):
Python 2.7.3 (default, Feb 27 2014, 19:58:35) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> d = {'size': 'large', 'quantity': 6} >>> il = d.items() >>> it = d.iteritems() >>> vi = d.viewitems() >>> il [('quantity', 6), ('size', 'large')] >>> it <dictionary-itemiterator object at 0x7fe555159f18> >>> vi dict_items([('quantity', 6), ('size', 'large')])
Test 2 (Python 3.4.1):
Python 3.4.1 (default, Aug 12 2014, 16:43:01) [GCC 4.9.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> d = {'size': 'large', 'quantity': 6} >>> il = d.items() >>> it = d.iteritems() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'dict' object has no attribute 'iteritems' >>> vi = d.viewitems() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'dict' object has no attribute 'viewitems' >>> il dict_items([('size', 'large'), ('quantity', 6)])
You can see that in Python 3.x, the two methods iteritems() and viewitems() have been abolished, and the result of item() is Consistent with viewitems() in 2.x.
2.x The content returned by iteritems() and viewitems() can be traversed using for. As shown below
>>> for k, v in it: ... print k, v ... quantity 6 size large >>> for k, v in vi: ... print k, v ... quantity 6 size large
What is the difference between the two? viewitems() returns the view object, which can reflect changes in the dictionary. For example, in the above example, if you add a key-value combination to d before using the two variables it and vi, the difference will be easy to see. .
>>> it = d.iteritems() >>> vi = d.viewitems() >>> d['newkey'] = 'newvalue' >>> d {'newkey': 'newvalue', 'quantity': 6, 'size': 'large'} >>> vi dict_items([('newkey', 'newvalue'), ('quantity', 6), ('size', 'large')]) >>> it <dictionary-itemiterator object at 0x7f50ab898f70> >>> for k, v in vi: ... print k, v ... newkey newvalue quantity 6 size large >>> for k, v in it: ... print k, v ... Traceback (most recent call last): File "<stdin>", line 1, in <module> RuntimeError: dictionary changed size during iteration
In the third line, we inserted a new element into d, vi can continue to traverse, and the new traversal can reflect the changes in d, but when traversing it, an error message appears in dictionary The size changed during traversal and the traversal failed.
To summarize, in 2.x, the items() method was originally used, but because it was too wasteful of memory, the iteritems() method was added to return an iterator. In 3.x, the items() method was added. The behavior of () was modified to return a view object, so that the object returned can also reflect changes in the original dictionary. At the same time, the backward compatibility feature of viewitems() was added in 2.7.
So in 3.x there is no need to worry about the differences between the three, because only one items() method is retained.
I believe that the examples described in this article have certain reference value for everyone's Python programming.
【Related Recommendations】
1. Special Recommendation: "php Programmer Toolbox" V0.1 version download
3. Basic introduction to Python items() method
4. Instance of item() function in Python traversing dictionary
5. Introducing three methods of accessing dictionary
6. The difference between iteriitems and items in sorted
The above is the detailed content of Detailed explanation of the usage of items() series functions in Python. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PS "Loading" problems are caused by resource access or processing problems: hard disk reading speed is slow or bad: Use CrystalDiskInfo to check the hard disk health and replace the problematic hard disk. Insufficient memory: Upgrade memory to meet PS's needs for high-resolution images and complex layer processing. Graphics card drivers are outdated or corrupted: Update the drivers to optimize communication between the PS and the graphics card. File paths are too long or file names have special characters: use short paths and avoid special characters. PS's own problem: Reinstall or repair the PS installer.

Solving the problem of slow Photoshop startup requires a multi-pronged approach, including: upgrading hardware (memory, solid-state drive, CPU); uninstalling outdated or incompatible plug-ins; cleaning up system garbage and excessive background programs regularly; closing irrelevant programs with caution; avoiding opening a large number of files during startup.

A PS stuck on "Loading" when booting can be caused by various reasons: Disable corrupt or conflicting plugins. Delete or rename a corrupted configuration file. Close unnecessary programs or upgrade memory to avoid insufficient memory. Upgrade to a solid-state drive to speed up hard drive reading. Reinstalling PS to repair corrupt system files or installation package issues. View error information during the startup process of error log analysis.

<p>The next page function can be created through HTML. The steps include: creating container elements, splitting content, adding navigation links, hiding other pages, and adding scripts. This feature allows users to browse segmented content, displaying only one page at a time, and is suitable for displaying large amounts of data or content. </p>

"Loading" stuttering occurs when opening a file on PS. The reasons may include: too large or corrupted file, insufficient memory, slow hard disk speed, graphics card driver problems, PS version or plug-in conflicts. The solutions are: check file size and integrity, increase memory, upgrade hard disk, update graphics card driver, uninstall or disable suspicious plug-ins, and reinstall PS. This problem can be effectively solved by gradually checking and making good use of PS performance settings and developing good file management habits.

The reason for slow PS loading is the combined impact of hardware (CPU, memory, hard disk, graphics card) and software (system, background program). Solutions include: upgrading hardware (especially replacing solid-state drives), optimizing software (cleaning up system garbage, updating drivers, checking PS settings), and processing PS files. Regular computer maintenance can also help improve PS running speed.

PS card is "Loading"? Solutions include: checking the computer configuration (memory, hard disk, processor), cleaning hard disk fragmentation, updating the graphics card driver, adjusting PS settings, reinstalling PS, and developing good programming habits.

There are three ways to export PDFs in batches on PS: use PS action functions: record and open files and export PDF actions, and execute actions in a loop. With the help of third-party software: use file management software or automation tools to specify the input and output folders and set the file name format. Use scripts: Write scripts to customize batch export logic, but programming knowledge is required.
