【Python】白话理解:默认字典collections.defaultdict

(1)浅层认知

collections是python内建标准库的集合模块,功能十分强大。
defaultdict是模块中的默认字典对象。

(2)最初的目的

为什么叫默认字典,就是为了解决,当外部调取该字典某个不存在的键时,会根据当前字典元素类型,返回对应的空值。

  • 例如,字典元素都是string,返回空值是"";
  • 再比如,字典元素都是list,返回空值是[];
  • 再比如,字典元素都是tuple,返回空值是();
  • 再比如,字典元素都是set,返回空值是set();

(3)第一个参数:工厂函数类型

以此衍生出,给定默认字典的第1个参数,定义了这个新创建的字典元素到底是什么类型的。

  • dict = collections.defaultdict(str)
  • dict = collections.defaultdict(list)
  • dict = collections.defaultdict(tuple)
  • dict = collections.defaultdict(set)

(4)列表特性字典:同键整合,物以类聚,保留每个元素(列表强调个体)

【使用场景】快速合并元组对列表
请注意,这里使用的是列表的append方法,就是即便元素相同也记录。

>>> old = [('yellow', 2), ('blue', 4), ('yellow', 1), ('blue', 1), ('red', 2)]
>>> new = defaultdict(list)
>>> for key, value in old:
	new[key].append(value)
 
>>> new.items()
dict_items([('yellow', [2, 1]), ('blue', [4, 1]), ('red', [2])])
>>> sorted(new.items())
[('blue', [4, 1]), ('red', [2]), ('yellow', [2, 1])]

(5)集合特性字典:同键整合,相同元素合并(集合强调集体)

【使用场景】快速合并集合对字典
请注意,当前键值对的增加是使用的集合方法add,即只记录不同值,相同值不记录。

>>> colors = [('yellow', 2), ('blue', 4), ('yellow', 1), ('blue', 4), ('yellow', 2)]
>>> color_set = defaultdict(set)
>>> for key, value in colors:
	color_set[key].add(value)
	
>>> color_set.items()
dict_items([('yellow', {1, 2}), ('blue', {4})])
>>> sorted(color_set.items())
[('blue', {4}), ('yellow', {1, 2})]

(6)计数巧用

(6-1)数字特性字典:可对字符串字母键整合计数(数字就是加和,无论整浮)

【使用场景】int类型的合并是加和

>>> string = 'nobugshahaha'
>>> count = defaultdict(int)
>>> for key in string:
	count[key] += 1
 
>>> count.items()
dict_items([('n', 1), ('o', 1), ('b', 1), ('u', 1), ('g', 1), ('s', 1), ('h', 3), ('a', 3)])
>>> sorted(count.items())
[('a', 3), ('b', 1), ('g', 1), ('h', 3), ('n', 1), ('o', 1), ('s', 1), ('u', 1)]

(6-2)计数实际可用集合模块的另一个对象:Counter

专业的计数器,直接对字符串字母计数。

from collections import Counter
>>> count2 = Counter(string)
>>> count2
Counter({'h': 3, 'a': 3, 'n': 1, 'o': 1, 'b': 1, 'u': 1, 'g': 1, 's': 1})
>>> count2.items()
dict_items([('n', 1), ('o', 1), ('b', 1), ('u', 1), ('g', 1), ('s', 1), ('h', 3), ('a', 3)])
>>> count2.most_common()
[('h', 3), ('a', 3), ('n', 1), ('o', 1), ('b', 1), ('u', 1), ('g', 1), ('s', 1)]

参考引用:【Python】详解 collections.defaultdict

  • 10
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值