Home Backend Development Python Tutorial Detailed explanation of the usage of items() series functions in Python

Detailed explanation of the usage of items() series functions in Python

May 17, 2017 pm 03:11 PM
dictionary items() python usage

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 = &#39;<{name}{attrs}>{value}</{name}>&#39;.format( 
      name = name, 
      attrs = attr_str, 
      value = html.escape(value)) 
  return element 
make_elements(&#39;item&#39;, &#39;Albatross&#39;, size=&#39;large&#39;, quantity=6) 
make_elements(&#39;p&#39;, &#39;<spam>&#39;)
Copy after login

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 = {&#39;size&#39;: &#39;large&#39;, &#39;quantity&#39;: 6} 
>>> d.items() 
[(&#39;quantity&#39;, 6), (&#39;size&#39;, &#39;large&#39;)]
Copy after login

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 = {&#39;size&#39;: &#39;large&#39;, &#39;quantity&#39;: 6} 
>>> il = d.items() 
>>> it = d.iteritems() 
>>> vi = d.viewitems() 
>>> il 
[(&#39;quantity&#39;, 6), (&#39;size&#39;, &#39;large&#39;)] 
>>> it 
<dictionary-itemiterator object at 0x7fe555159f18> 
>>> vi 
dict_items([(&#39;quantity&#39;, 6), (&#39;size&#39;, &#39;large&#39;)])
Copy after login

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 = {&#39;size&#39;: &#39;large&#39;, &#39;quantity&#39;: 6} 
>>> il = d.items() 
>>> it = d.iteritems() 
Traceback (most recent call last): 
 File "<stdin>", line 1, in <module> 
AttributeError: &#39;dict&#39; object has no attribute &#39;iteritems&#39; 
>>> vi = d.viewitems() 
Traceback (most recent call last): 
 File "<stdin>", line 1, in <module> 
AttributeError: &#39;dict&#39; object has no attribute &#39;viewitems&#39; 
>>> il 
dict_items([(&#39;size&#39;, &#39;large&#39;), (&#39;quantity&#39;, 6)])
Copy after login

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

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[&#39;newkey&#39;] = &#39;newvalue&#39; 
>>> d 
{&#39;newkey&#39;: &#39;newvalue&#39;, &#39;quantity&#39;: 6, &#39;size&#39;: &#39;large&#39;} 
>>> vi 
dict_items([(&#39;newkey&#39;, &#39;newvalue&#39;), (&#39;quantity&#39;, 6), (&#39;size&#39;, &#39;large&#39;)]) 
>>> 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
Copy after login

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

2. Free Python video tutorial

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!

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 programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

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