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中的ConfigParser模块使用详解

1.基本的读取配置文件     -read(filename) 直接读取ini文件内容     -sections() 得到所...

Python多线程同步---文件读写控制方法

Python多线程同步---文件读写控制方法

1、实现文件读写的文件ltz_schedule_times.py #! /usr/bin/env python #coding=utf-8 import os def ReadTi...

python3+dlib实现人脸识别和情绪分析

python3+dlib实现人脸识别和情绪分析

一、介绍 我想做的是基于人脸识别的表情(情绪)分析。看到网上也是有很多的开源库提供使用,为开发提供了很大的方便。我选择目前用的比较多的dlib库进行人脸识别与特征标定。使用python也...

通过实例学习Python Excel操作

通过实例学习Python Excel操作

这篇文章主要介绍了通过实例学习Python Excel操作,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.python 读取Exc...

Python绘图实现显示中文

Python绘图实现显示中文

我们用Python进行数据可视化,绘制各种图形时,往往会遇到明明数据都设置对了,但是在图形上显示不出来。例如绘制直方图,程序如下: plt.hist(roll_list, bins=...