Examples of usages of dictionary items () series functions in Python _python

Source: Internet
Author: User
Tags comments stdin in python

This example describes the use of the Dictionary items () series function in Python, which has a good reference value for Python programming. The specific analysis is as follows:

Let's take a look at an example:

Import HTML  # available only in Python 3.x 
def make_elements (name, Value, **attrs): 
  keyvals = ['%s= '%s '% it EM 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 the program is very simple, is to generate HTML tags, note that the HTML module can only be in Python 3.x.

At first I just noticed that the keyvals of this dictionary type variable was built in the form of a Tag property list. Two%s corresponds to an item, so I looked up the relevant data and pulled out quite a lot of things, summed up here.

Note: All of the following versions of the Python interpreter, 2.x correspond to the 2.7.3,3.x corresponding to the 3.4.1
In the Python 2.x, the method for items in the official document is to show that a list of (key, value) pairs is generated, as follows:

>>> d = {' size ': ' Large ', ' Quantity ': 6} 
>>> D.items () 
[(' Quantity ', 6], (' Size ', ' large ')] 

In the search process, I have no intention of seeing such a problem on StackOverflow: What's the difference between Dict.items () and Dict.iteritems ()? , the first answer roughly means this:

"At first the items () were to return a list that contained all of the dict elements like the one above, but because it was so wasteful of memory, it was later added (note: in Python 2.2) Iteritems (), Iterkeys (), itervalues () This set of functions that return a iterator to save memory, but in 3.x the items () themselves return such iterator, so the act of items () in 3.x is consistent with the 2.x iteritems () behavior, Iteritems () this A set of functions is abolished. ”

But what's even more interesting is that, although the answer is accepted, the comments below point out that this is not accurate, and that the behavior of items (in 3.x) is not the same as the 2.x Iteritems (), which actually returns a "full Sequence-protocol Object ", which can reflect the change of dict, and later added another function in Python 2.7 viewitems () and 3.x of this behavior consistent
To confirm the comments, I did the following tests to see the Python version used in the test:

Test 1 (Python 2.7.3):

Python 2.7.3 (default, Feb 2014, 19:58:35)  
[GCC 4.6.3] on linux2 
Type ' help ', ' copyright ', ' credits ' or ' Licens E "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 2014, 16:43:01)  
[GCC 4.9.0] on Linux 
Type ' help ', ' copyright ', ' credits ' or ' license For the more information. 
>>> d = {' size ': ' Large ', ' Quantity ': 6} 
>>> il = d.items () 
>>> it = d.iteritems () 
Traceback (most recent): 
 File "<stdin>", line 1, in <module> 
attributeerror: ' Dict ' object h As no attribute ' Iteritems ' 
>>> vi = d.viewitems () 
Traceback (most recent call last): 
 File "<st Din> ", line 1, in <module> 
attributeerror: ' Dict ' object has no attribute ' Viewitems ' 
>>> il< C14/>dict_items ([' Size ', ' large '), (' Quantity ', 6)]) 

As you can see in the Python 3.x, both Iteritems () and Viewitems () have been abolished, and item () has the same result as the 2.x viewitems ().
The contents returned by Iteritems () and Viewitems () in 2.x can be traversed with for, as follows

>>> for K, V in it: 
...  Print K, v ...  
Quantity 6 
size Large 
>>> for K, V in VI: 
...  Print K, v ...  
Quantity 6 
size Large 

Where is the difference between the two? Viewitems () Returns the View object, which reflects the dictionary changes, such as the above example, if the use of it and VI of the two variables before the D to add a key-value combination, the difference is easy to see.

>>> it = D.iteritems () 
>>> VI = d.viewitems () 
>>> d[' newkey '] = ' newvalue ' 
>& Gt;> 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): 
 File "<stdin>", line 1, in <module> 
runtimeerror:dictionary cha Nged size during iteration 

In the third line, we like to insert a new element in D, vi can continue to traverse, and the new traversal can reflect the change of D, but in traversing it, the error prompts dictionary in the traversal of the size of the change, traversal failure.

To sum up, in 2.x, originally is the items () this method, but because of too much waste of memory, so added the Iteritems () method, to return a iterator, in the 3.x to change the behavior of items () to return a View object, let it return Back objects can also reflect the changes in the original dictionary, while in 2.7 add the Viewitems () backward-compatible feature.
So in 3.x there is no need to dwell on the differences between the three, because only one of the items () method is retained.

It is believed that the example mentioned in this article has some reference value for the Python program design.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.