Python标准库使用OrderedDict类的实例讲解

yipeiwu_com6年前Python基础

目标:创建一个字典,记录几对python词语,使用OrderedDict类来写,并按顺序输出。

写完报错:

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

代码如下:

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() + '.')
~   

结果for循环的for写成from了……总是出现简单的错误。

最终,正确代码如下:

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() + '.')

第一行,从模块collections中导入OrderedDict类;

第二行,创建了OrderedDict类的一个实例,并将其存储到python_terms中,也就是创建了一个空字典;

第三至五行,为字典添加键值对;

最后,循环输出结果。

运行结果:

[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.

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对【听图阁-专注于Python设计】的支持。如果你想了解更多相关内容请查看下面相关链接

相关文章

Python实现提取谷歌音乐搜索结果的方法

本文实例讲述了Python实现提取谷歌音乐搜索结果的方法。分享给大家供大家参考。具体如下: Python的简单脚本,用于提取谷歌音乐搜索页面中的歌曲信息,包括歌曲名,作者,专辑名,现在链...

python遍历数组的方法小结

本文实例总结了python遍历数组的方法。分享给大家供大家参考。具体分析如下: 下面介绍两种遍历数组的方法,一种是直接通过for in 遍历数组,另外一种是通过rang函数先获得数组长度...

Python 文件操作实现代码

open(filename,mode,buffer) 其中第一个参数是要打开的文件的文件名,必选;第二个是打开方式,可选;第三个为缓冲区,可选。默认情况下是以“读”模式打开文件。该函数返...

Python树莓派学习笔记之UDP传输视频帧操作详解

本文实例讲述了Python树莓派学习笔记之UDP传输视频帧操作。分享给大家供大家参考,具体如下: 因为我在自己笔记本电脑上没能成功安装OpenCV-Contrib模块,因此不能使用人脸识...

python if not in 多条件判断代码

python if not in 多条件判断代码

百度作业帮提问: python if not in 多条件 判断怎么写 s = ['1','2'] 判断条件 sta = "12345" 正常的是这样的, if "1" not in s...