当前第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字典的操作总结(附示例)的详细内容,更多文章请关注木庄网络博客!!
返回前面的内容
相关阅读 >>
django中数据库设置的详细介绍(代码示例)
Python中关于装饰器的学习
Python入口函数是什么
怎么查看Python安装路径
win10怎么下载Python并安装
Python是一种跨平台、开源、免费的高级动态编程语言,对么
Python基础知识一:网络通信数据传输
Python中eval是什么意思?
Python编程中notimplementederror的使用方法_Python
Python下载后怎么用
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python字典的操作总结(附示例)