dict字典技巧

dict.get(key, default=None)
参数1:key – 字典中要查找的键。
参数2:default – 如果指定键的值不存在时,返回该默认值。
返回值:返回指定键的值,如果键不在字典中返回默认值 None 或设置的默认值。

在这里插入图片描述


# o一个技巧:未知元素个数时
# seg_novel:的值如上图所示

for word_cow in seg_novel:
    for word in word_cow:
        count[word] = count.get(word,0) + 1  // this the point
li = list(count.items())
li.sort(key=lambda x:x[1], reverse=True)
for i in range(0,20):
    key,value = li[i]
    print('{:<3}{:<6}{:>5}'.format(i+1,key,value))
114377
212238
3  韦小宝    9908
4  武功     6744
56590
6  郭靖     6568
7  一声     6520
8  杨过     6167
9  师父     6071
105821
115706
12 心中     5687
13 不知     5541
14 黄蓉     5195
155167
16 令狐冲    5052
17 心想     5033
184796
19 张无忌    4786
204497

dict.items()
Python 字典(Dictionary) items() 函数以列表返回可遍历的(键, 值) 元组数组。

# dict转化为list
xlist = list(dic.items()) # 注意要再用list保住

猜你喜欢

转载自blog.csdn.net/weixin_44227389/article/details/113872836