当前位置:Gxlcms > Python > PythonTipsandTraps(二)

PythonTipsandTraps(二)

时间:2021-07-01 10:21:17 帮助过:34人阅读

6、collections 模块还提供有OrderedDict,用于获取有序字典

import collections
d = {'b':3, 'a':1,'x':4 ,'z':2}
dd = collections.OrderedDict(d)for key, value in dd.items(): PRint key, value#b 3#a 1#x 4#z 2

7、collections 模块的defaultdict 模块

defaultdict类就像是dict,但它是使用一个类型(也可以是没有参数的可调用函数,函数返回结果作为默认值)来初始化,它接受一个类型作为参数,当所访问的键不存在时,可实例化一个值作为默认值

import collections
aa = collections.defaultdict(list)
aa['a']# []aa['b'].append(1)print aa['b']# [1]

以上就是PythonTipsandTraps(二)的内容,更多相关内容请关注PHP中文网(www.gxlcms.com)!

人气教程排行