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程序中,用if语句实现: age = 20 if a...

python通过shutil实现快速文件复制的方法

本文实例讲述了python通过shutil实现快速文件复制的方法。分享给大家供大家参考。具体如下: python通过shutil实现快速文件拷贝,shutil使用起来非常方便,可以通过p...

Python的randrange()方法使用教程

 choice()方法从一个列表,元组或字符串返回一个随机项。 语法 以下是choice()方法的语法: choice( seq ) 注意:此函数是无法直接访问的,所...

Python的语言类型(详解)

Python 是强类型的动态脚本语言 。 强类型:不允许不同类型相加 动态:不使用显示数据类型声明,且确定一个变量的类型是在第一次给它赋值的时候 脚本语言:一般也是解释型语言,运行代码只...

python3获取当前目录的实现方法

1. 以前的方法 如果是要获得程序运行的当前目录所在位置,那么可以使用os模块的os.getcwd()函数。 如果是要获得当前执行的脚本的所在目录位置,那么需要使用sys模块的sys.p...