Python basic tutorial: Python standard library uses the OrderedDict class to explain examples

@This article comes from the public number: csdn2299. If you like, you can follow the public number. The programmers' school
today will share an explanation about the use of the OrderedDict class in the Python standard library. The editor feels that the content is quite good. It has a good reference value. Friends who need it follow the editor to see it.
Goal: Create a dictionary, record several pairs of python words, use the OrderedDict class to write, and output in order.

Error after writing:

[root@centos7 tmp]# python python_terms.py 
 File "python_terms.py", line 9
  from name,language in python_terms.items():
       ^
SyntaxError: invalid syntax

code show as below:

from collections import OrderedDict
python_terms = OrderedDict()
python_terms['key'] = 'vlaue'
python_terms['if']  = 'match'
python_terms['from'] = 'import'
from name,language in python_terms.items():
  print("python have many terms " + name.title() +
    language.title() + '.')
~

As a result, the for loop is written as from ... There are always simple errors.

Finally, the correct code is as follows:

from collections import OrderedDict
python_terms = OrderedDict()
python_terms['key'] = 'vlaue'
python_terms['if']  = 'match'
python_terms['from'] = 'import'
for name,language in python_terms.items():
  print("python have many terms " + name.title() +
    " " + language.title() + '.')

The first line, import the OrderedDict class from the module collections;

In the second line, an instance of the OrderedDict class is created and stored in python_terms, that is, an empty dictionary is created;

The third to fifth lines add key-value pairs to the dictionary;

Finally, the results are output in a loop.

operation result:

[root@centos7 tmp]# python python_terms.py 
python have many terms Key Vlaue.
python have many terms If Match.
python have many terms From Import.

Thank you very much for reading
. When I chose to study python at university, I found that I ate a bad computer foundation. I did n’t have an academic qualification. This is
nothing to do. I can only make up for it, so I started my own counterattack outside of coding. The road, continue to learn the core knowledge of python, in-depth study of computer basics, sorted out, if you are not willing to be mediocre, then join me in coding, and continue to grow!
In fact, there are not only technology here, but also things beyond those technologies. For example, how to be an exquisite programmer, rather than "cock silk", the programmer itself is a noble existence, isn't it? [Click to join] Want to be yourself, want to be a noble person, come on!

Published 45 original articles · praised 16 · 20,000+ views

Guess you like

Origin blog.csdn.net/chengxun03/article/details/105522228