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

作者:zsx0728 时间:2022-07-17 22:27:31 

目标:创建一个字典,记录几对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.

来源:https://blog.csdn.net/zsx0728/article/details/81234532

标签:python,ordereddict,标准库
0
投稿

猜你喜欢

  • python fabric实现远程操作和部署示例

    2021-07-18 14:22:14
  • Python中os模块的12种用法总结

    2023-12-01 07:16:28
  • 数据仓库基本报表制作过程中的SQL写法

    2008-11-25 12:17:00
  • ASP 调用带参数输出的COM接口

    2011-03-17 10:59:00
  • 使用Python判断质数(素数)的简单方法讲解

    2022-07-23 22:34:19
  • Python实现统计给定列表中指定数字出现次数的方法

    2023-02-04 09:50:29
  • Python语言实现SIFT算法

    2022-12-30 17:58:14
  • asp产生不重复的随机数

    2008-06-03 13:29:00
  • Python实战小程序利用matplotlib模块画图代码分享

    2021-08-27 18:31:47
  • 经典的退出浏览器弹窗代码

    2008-07-30 12:48:00
  • vue如何根据权限生成动态路由、导航栏

    2024-05-05 09:25:43
  • Ubuntu 下 vim 搭建python 环境 配置

    2022-04-27 21:25:17
  • python实现人机对战的五子棋游戏

    2021-07-05 04:36:03
  • Git分支管理策略

    2022-02-18 13:11:38
  • Python的Flask框架中使用Flask-Migrate扩展迁移数据库的教程

    2024-01-19 06:38:45
  • Django 解决上传文件时,request.FILES为空的问题

    2021-10-21 19:37:41
  • 利用python将 Matplotlib 可视化插入到 Excel表格中

    2023-09-26 09:03:25
  • pytorch和numpy默认浮点类型位数详解

    2021-11-10 10:19:49
  • jsp下页面跳转的几种方法小结

    2023-07-22 00:38:07
  • 学会sql数据库关系图(Petshop)

    2024-01-28 18:43:23
  • asp之家 网络编程 m.aspxhome.com