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

yipeiwu_com5年前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箱型图处理离群点的例子

首先我们简单地区分一下离群点(outlier)以及异常值(anomaly): 离群点: 异常值: 个人觉着异常值和离群点是两个不同的概念,当然大家在数据预处理时对于这两个概念不做细致...

举例详解Python中threading模块的几个常用方法

threading.Thread Thread 是threading模块中最重要的类之一,可以使用它来创建线程。有两种方式来创建线程:一种是通过继承Thread类,重写它的run方法;另...

python图片二值化提高识别率代码实例

python图片二值化提高识别率代码实例

这篇文章主要介绍了python图片二值化提高识别率代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 代码如下 import...

使用Pyinstaller的最新踩坑实战记录

前言 将py编译成可执行文件需要使用PyInstaller,之前给大家介绍了关于利用PyInstaller将python程序.py转为.exe的方法,在开始本文之前推荐大家可以先看下这篇...

Python操作MySQL数据库9个实用实例

Python操作MySQL数据库9个实用实例

在Windows平台上安装mysql模块用于Python开发 用python连接mysql的时候,需要用的安装版本,源码版本容易有错误提示。下边是打包了32与64版本。 MySQL-py...