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设计】的支持。如果你想了解更多相关内容请查看下面相关链接

相关文章

TFRecord格式存储数据与队列读取实例

TFRecord格式存储数据与队列读取实例

Tensor Flow官方网站上提供三种读取数据的方法 1. 预加载数据:在Tensor Flow图中定义常量或变量来保存所有数据,将数据直接嵌到数据图中,当训练数据较大时,很消耗内存...

python用户评论标签匹配的解决方法

python用户评论标签匹配的解决方法

我们观察用户评论发现:属性词往往和情感词伴随出现,原因是用户通常会在描述属性时表达情感,属性是情感表达的对象。还发现:属性词和专用情感词基本都是名词或形容词(形谓词)。 算法流程图如下:...

pandas 转换成行列表进行读取与Nan处理的方法

pandas中有时需要按行依次对.csv文件读取内容,那么如何进行呢? 我们来完整操作一遍,假设我们已经有了一个.csv文件。 # 1.导入包 import pandas as p...

python os模块简单应用示例

本文实例讲述了python os模块简单应用。分享给大家供大家参考,具体如下: 举例中的目录形式如下所示: In [36]: pwd Out[36]: '/home/python/D...

在SAE上部署Python的Django框架的一些问题汇总

花了些工夫将碎片网部署到了SAE,中途遇到各类问题。感觉SAE看上去很美,实际上却并不是太成熟(至少python版如此)。 下面记录下我遇到的一些主要问题以及解决方法。 django版本...