Python OrderedDict 类

字典让你能够将信息关联起来,然后它们不记录你们添加键值对的顺序,要创建字典和记录添加键-值对的顺序,可使用模块collections中的OrderedDict类,如下面例子所示”

from collections import OrderedDict # 从模块collections中导入OrderedDict类
favorite_languages = OrderedDict() # 创建OrderedDict类的一个实例,并将其存储到favorite_languages。
favorite_languages['jen'] = 'python' # 每次一个键值对的顺序添加
favorite_languages['sarah'] = 'c'
favorite_languages['edward'] = 'ruby'
favorite_languages['phil'] = 'python'
for name, language in favorite_languages.items():
    print(name.title() + " 's favorite language is " + language)

//输出结果为:
Jen 's favorite language is python
Sarah 's favorite language is c
Edward 's favorite language is ruby
Phil 's favorite language is python

# 参照书籍:Python 编程从入门到实践 Eric Mattes 著,袁国忠 译
发布了24 篇原创文章 · 获赞 0 · 访问量 830
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 书香水墨 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览