当前第2页 返回上一页
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | from collections import OrderedDict
d = {}
d[ 'Tom' ]= 'A'
d[ 'Jack' ]= 'B'
d[ 'Leo' ]= 'C'
d[ 'Alex' ]= 'D'
print ( '无序字典(dict):' )
for k,v in d.items():
print (k,v)
d1 = OrderedDict()
d1[ 'Tom' ]= 'A'
d1[ 'Jack' ]= 'B'
d1[ 'Leo' ]= 'C'
d1[ 'Alex' ]= 'D'
print ( '\n有序字典(OrderedDict):' )
for k,v in d1.items():
print (k,v)
|
输出的结果为:
1 2 3 4 5 6 7 8 9 10 | 无序字典(dict):
Leo C
Jack B
Tom A
Alex D
有序字典(OrderedDict):
Tom A
Jack B
Leo C
Alex D
|
默认字典collections.defaultdict
??collections.defaultdict
是Python内建dict
类的一个子类,第一个参数为default_factory属性提供初始值,默认为None
。它覆盖一个方法并添加一个可写实例变量。它的其他功能与dict
相同,但会为一个不存在的键提供默认值,从而避免KeyError
异常。
??我们以统计列表中单词的词频为例,展示collections.defaultdict
的优势。
??一般情形下,我们统计列表中的单词词频代码为:
1 2 3 4 5 6 7 8 9 10 | words = [ 'sun' , 'moon' , 'star' , 'star' ,\
'star' , 'moon' , 'sun' , 'star' ]
freq_dict = {}
for word in words:
if word not in freq_dict.keys():
freq_dict[word] = 1
else :
freq_dict[word] += 1
for key, val in freq_dict.items():
print (key, val)
|
输出结果如下:
??使用collections.defaultdict
,代码可以优化:
1 2 3 4 5 6 7 8 9 10 11 | from collections import defaultdict
words = [ 'sun' , 'moon' , 'star' , 'star' ,\
'star' , 'moon' , 'sun' , 'star' ]
freq_dict = defaultdict(int)
for word in words:
freq_dict[word] += 1
for key, val in freq_dict.items():
print (key, val)
|
其它默认初始值可以为set,list,dict等。
以上就是Python字典的操作总结(附示例)的详细内容,更多文章请关注木庄网络博客!!
返回前面的内容
相关阅读 >>
Python函数之divmod数字处理函数
Python3将Python代码打包成exe文件的方法
Python实现连接数据库的方法介绍
Python属于开源语言吗
Python读取csv文件并把文件放入一个list中的实例讲解
如何用Python爬虫获取那些价值博文
浅谈Python日志的配置文件路径问题
三种常用的Python中文分词工具
Python如何输入十个学生的成绩
介绍使用Python的statsmodels模块拟合arima模型
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python字典的操作总结(附示例)