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保存网页上的图片或者保存页面为截图

Python保存网页图片 这个是个比较简单的例子,网页中的图片地址都是使用'http://。。。。.jpg'这种方式直接定义的。 使用前,可以先建立好一个文件夹用于保存图片,本例子中使用...

Python enumerate函数遍历数据对象组合过程解析

这篇文章主要介绍了Python enumerate函数遍历数据对象组合过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 介绍...

Python中判断子串存在的性能比较及分析总结

起步 对于子串搜索,Python提供了多种实现方式:in, find, index, __contains__,对其进行性能比较: import timeit def in_(s...

python 实现视频流下载保存MP4的方法

如下所示: # -*- coding:utf-8 -*- import sys import os from glob import glob import requests...

Python 实现Windows开机运行某软件的方法

Python 实现Windows开机运行某软件的方法

开机运行:随系统启动的应用程序,当系统启动之后会自动加载的应用 在注册表中添加启动项便可实现开机启动。 代码如下: # -*- coding:utf-8 -*- import win...