Example of the usage of dictionary items () series functions in Python, pythondictionary

Source: Internet
Author: User

Example of the usage of dictionary items () series functions in Python, pythondictionary

This article describes the usage of dictionary items () series functions in Python and provides reference for Python program design. The specific analysis is as follows:

Let's look at an example:

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 to generate HTML tags. Note that the html module can only be used in Python 3. x.

At first, I just noticed that the method of constructing the dictionary type variable keyvals that generates the tag attribute list is very interesting. Two % s correspond to one item, so I checked the relevant materials, A lot of things have been pulled out, and we will summarize them here.

NOTE: For the following versions of Python interpreters, 2.x corresponds to 2.7.3 and 3.x corresponds to 3.4.1.
In Python 2.x, the items method is described as follows: generate a list of (key, value) pairs, as shown below:

>>> d = {'size': 'large', 'quantity': 6} >>> d.items() [('quantity', 6), ('size', 'large')] 

In the search process, I have no intention to see the stackoverflow question: What is the difference between dict. items () and dict. iteritems? The first answer roughly indicates the following:

"At first items () is to return a list containing all the elements of dict as above, but this is a waste of memory, so it was added later (note: the iteritems (), iterkeys (), and itervalues () functions that appear at the beginning of Python 2.2 are used to return an iterator to save memory, but items () in 3.x () this iterator is returned, so the items () behavior in 3.x is the same as that in 2.x iteritems (), and The iteritems () function is abolished."

However, even though this answer is accepted, the comments below indicate that this statement is not accurate. In 3.x, the items () behavior is different from that in 2.x iteritems, it actually returns a "full sequence-protocol object", which reflects the changes of dict. Later, another function viewitems () was added to Python 2.7 () this behavior is consistent with that of 3.x.
To confirm the comment, I did the following test. Note that the Python version used in the test is:

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)]) 

In Python 3.x, iteritems () and viewitems () methods have been abolished, and item () returns the same result as viewitems () in 2.x.
2. The iteritems () and viewitems () returned content in x 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 the changes of the dictionary. For example, in the preceding example, before using the it and vi variables, add a key-value combination to d. The difference is 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 row, we insert a new element like d. vi can continue to traverse, and the new traversal can reflect the changes of d, but when traversing it, an error is reported, indicating that the size of the dictionary changes during traversal and the traversal fails.

To sum up, in 2.x, it was originally the items () method, but the iteritems () method was added to return an iterator because it is too memory-consuming, modify the items () Action in 3.x to return a view object, so that the returned object can also reflect the change of the original dictionary, and add viewitems () in 2.7 () backward compatible with this feature.
Therefore, in 3.x, there is no need to worry about the differences between the three, because only one items () method is retained.

I believe the examples described in this article have some reference value for everyone's Python program design.


A usage of the print function in python

This can be changed.
List1 = ['dd']
File1 = open('text_file.txt ', 'w ')
File1.write (str (List1 ))
Fiel1.close ()

# Print (List, file = file1)

Python 25 round (,) function usage

Yes, because 2. x and 3. x have been adjusted on the data type, depending on the content updated after 3. x.
There are many differences between 2. x and 3. x. It is recommended to learn 2. x first, because 3. x is not yet popular.
We also recommend that you do not view them together. This will be confusing.
 

Related Article

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.