Python 3 collections.defaultdict() 与 dict的使用和区别
综述:
这里的defaultdict(function_factory)构建的是一个类似dictionary的对象,其中keys的值,自行确定赋值,但是values的类型,是function_factory的类实例,而且具有默认值。比如default(int)则创建一个类似dictionary对象,里面任何的values都是int的实例,而且就算是一个不存在的key, d[key] 也有一个默认值,这个默认值是int()的默认值0.
defaultdict
dict subclass that calls a factory function to supply missing values。
这是一个简短的解释
defaultdict属于内建函数dict的一个子类,调用工厂函数提供缺失的值。
比较晕,什么是工厂函数:
来自python 核心编程的解释
Python 2.2 统一了类型和类, 所有的内建类型现在也都是类, 在这基础之上, 原来的
所谓内建转换函数象int(), type(), list() 等等, 现在都成了工厂函数。 也就是说虽然他
们看上去有点象函数, 实质上他们是类。当你调用它们时, 实际上是生成了该类型的一个实
例, 就象工厂生产货物一样。
下面这些大家熟悉的工厂函数在老的Python 版里被称为内建函数:
int(), long(), float(), complex()
str(), unicode(), basestring()
list(), tuple()
type()
以前没有工厂函数的其他类型,现在也都有了工厂函数。除此之外,那些支持新风格的类
的全新的数据类型,也添加了相应的工厂函数。下面列出了这些工厂函数:
dict()
bool()
set(), frozenset()
object()
classmethod()
staticmethod()
super()
property()
file()
再看看它的使用:
- import collections
- s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
- d = collections.defaultdict(list)
- for k, v in s:
- d[k].append(v)
- list(d.items())
这里就开始有点明白了,原来defaultdict可以接受一个内建函数list作为参数。其实呢,list()本身是内建函数,但是再经过更新后,python里面所有东西都是对象,所以list改编成了类,引入list的时候产生一个类的实例。
还是不太明白,再看defaultdict的help解释
- class collections.defaultdict([default_factory[, ...]])
-
Returns a new dictionary-like object. defaultdict is a subclass of the built-in dict class. It overrides one method and adds one writable instance variable. The remaining functionality is the same as for the dict class and is not documented here.
首先说了,collections.defaultdict会返回一个类似dictionary的对象,注意是类似的对象,不是完全一样的对象。这个defaultdict和dict类,几乎是一样的,除了它重载了一个方法和增加了一个可写的实例变量。(可写的实例变量,我还是没明白)
The first argument provides the initial value for the default_factory attribute; it defaults to None. All remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments.
defaultdict objects support the following method in addition to the standard dict operations:
- __missing__(key)
-
If the default_factory attribute is None, this raises a KeyError exception with the key as argument.
If default_factory is not None, it is called without arguments to provide a default value for the given key, this value is inserted in the dictionary for the key, and returned.
-
主要关注这个话,如果default_factory不是None, 这个default_factory将以一个无参数的形式被调用,提供一个默认值给___missing__方法的key。 这个默认值将作为key插入到数据字典里,然后返回。
-
十分晕。有扯出了个__missing__方法,这个__missing__方法是collections.defaultdict()的内建方法。
If calling default_factory raises an exception this exception is propagated unchanged.
This method is called by the __getitem__() method of the dict class when the requested key is not found; whatever it returns or raises is then returned or raised by __getitem__().
Note that __missing__() is not called for any operations besides __getitem__(). This means that get() will, like normal dictionaries, return None as a default rather than using default_factory.
defaultdict objects support the following instance variable:
- default_factory
-
This attribute is used by the __missing__() method; it is initialized from the first argument to the constructor, if present, or to None, if absent.
看样子这个文档是难以看懂了。直接看示例:
- import collections
- s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
- # defaultdict
- d = collections.defaultdict(list)
- for k, v in s:
- d[k].append(v)
- # Use dict and setdefault
- g = {}
- for k, v in s:
- g.setdefault(k, []).append(v)
- # Use dict
- e = {}
- for k, v in s:
- e[k] = v
- ##list(d.items())
- ##list(g.items())
- ##list(e.items())
看看结果:
- list(d.items())
- [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
- >>> list(g.items())
- [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
- >>> list(e.items())
- [('blue', 4), ('red', 1), ('yellow', 3)]
- >>> d
- defaultdict(<class 'list'>, {'blue': [2, 4], 'red': [1], 'yellow': [1, 3]})
- >>> g
- {'blue': [2, 4], 'red': [1], 'yellow': [1, 3]}
- >>> e
- {'blue': 4, 'red': 1, 'yellow': 3}
- >>> d.items()
- dict_items([('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])])
- >>> d["blue"]
- [2, 4]
- >>> d.keys()
- dict_keys(['blue', 'red', 'yellow'])
- >>> d.default_factory
- <class 'list'>
- >>> d.values()
- dict_values([[2, 4], [1], [1, 3]])
可以看出
collections.defaultdict(list)使用起来效果和运用dict.setdefault()比较相似
python help上也这么说了
When each key is encountered for the first time, it is not already in the mapping; so an entry is automatically created using the default_factory function which returns an empty list. The list.append() operation then attaches the value to the new list. When keys are encountered again, the look-up proceeds normally (returning the list for that key) and the list.append() operation adds another value to the list. This technique is simpler and faster than an equivalent technique using dict.setdefault():
说这种方法会和dict.setdefault()等价,但是要更快。
有必要看看dict.setdefault()
- setdefault(key[, default])
-
If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.
如果这个key已经在dictionary里面存着,返回value.如果key不存在,插入key和一个default value,返回Default. 默认的defaults是None.
但是这里要注意的是defaultdict是和dict.setdefault等价,和下面那个直接赋值是有区别的。从结果里面就可以看到,直接赋值会覆盖。
从最后的d.values还有d[“blue”]来看,后面的使用其实是和dict的用法一样的,唯一不同的就是初始化的问题。defaultdict可以利用工厂函数,给初始keyi带来一个默认值。
这个默认值也许是空的list[] defaultdict(list), 也许是0, defaultdict(int).
再看看下面的这个例子。
defaultdict(int) 这里的d其实是生成了一个默认为0的带key的数据字典。你可以想象成 d[key] = int default (int工厂函数的默认值为0)
d[k]所以可以直接读取 d[“m”] += 1 就是d[“m”] 就是默认值 0+1 = 1
后面的道理就一样了。
- >>> s = 'mississippi'
- >>> d = defaultdict(int)
- >>> for k in s:
- ... d[k] += 1
- ...
- >>> list(d.items())
- [('i', 4), ('p', 2), ('s', 4), ('m', 1)]
【. . . . . .本博客仅作个人生活、工作、学习等的日常记录。说明: (1) 内容有参考其他博主、网页等,有因“懒”直接粘贴来,会备注出处。若遇雷同,或忘备注,并无故意抄袭之意,请诸“原主”谅解,很感谢您的辛勤"笔记"可供本人参考学习。 (2) 如遇同行,有参考学习者,因个人学识有限,不保证所写内容完全正确。您对本博文有任何的意见或建议,欢迎留言,感谢指正。 (3) 若您认为本主的全博客还不错,可以点击关注,便于互相学习。 (4) 感谢您的阅读,希望对您有一定的帮助。欢迎转载或分享,但请注明出处,谢谢。. . . . . .】
Python 3 collections.defaultdict() 与 dict的使用和区别的更多相关文章
- (转)Python 3 collections.defaultdict() 与 dict的使用和区别
原文:https://www.cnblogs.com/herbert/archive/2013/01/09/2852843.html 在Python里面有一个模块collections,解释是数据类型 ...
- Python collections.defaultdict() 与 dict的使用和区别
看样子这个文档是难以看懂了.直接看示例: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 import collections s = [('yellow', ...
- Python中collections.defaultdict()使用
一个小示例 from collections import defaultdict import json def tree(): return defaultdict(tree) users = t ...
- Python之collections.defaultdict
转自:http://www.jb51.net/article/88147.htm
- python collections defaultdict
class_counts = defaultdict(int) 一.关于defaultdict 在Python里面有一个模块collections,解释是数据类型容器模块.这里面有一个collect ...
- Python: dict setdault函数与collections.defaultdict()的区别
setdault用法 >>>dd={'hy':1,'hx':2} >>>cc=dd.setdefault('hz',1) >>>cc 返 ...
- python之collections模块(OrderDict,defaultdict)
前言: import collections print([name for name in dir(collections) if not name.startswith("_" ...
- Python collections.defaultdict 笔记
其实defaultdict 就是一个字典,只不过python自动的为它的键赋了一个初始值.这也就是说,你不显示的为字典的键赋初值python不会报错,看下实际例子. 比如你想计算频率 frequenc ...
- python初探-collections容器数据类型
collections容器数据类型是对基本数据类型的补充,简单介绍下计数器.有序字典.默认字典.可命名元祖.队列. 计数器(Counter) Counter是对字典类型的补充,用于追踪值得出现次数 c ...
随机推荐
- python连接mysql数据库遇到的问题
1.源代码: from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy ...
- python函数基础学习
函数的定义与调用: def 函数名(参数1,参数2): ‘’’函数注释’’’ print(‘函数体’) return 返回值 定 义:def关键字开关,空格之后接函数名和圆括号,最后冒号结尾 def ...
- 性能测试工具LoadRunner19-LR之Controller IP欺骗
概念 IP地址欺骗是指用户操作产生的IP数据包为伪造的源IP地址,以便冒充其他系统或发件人的身份.这是一种黑客的攻击形式,黑客使用一台计算机上网,而借用另外一台机器的IP地址,从而冒充另外一台机器与服 ...
- CentOS 6.5 & 7 的网络YUM源配置
中国科技大学CentOS 6.5的网络源 [base]name=CentOS-$releasever - Base#mirrorlist=http://mirrorlist.centos.org/?r ...
- jemeter+badboy录制脚本
Jmeter 是一个非常流行的性能测试工具,虽然与LoadRunner相比有很多不足,比如:它结果分析能力没有LoadRunner详细:很它的优点也有很多: l 开源,他是一款开源的免费软 ...
- Visual Studio 要求导入 pfx 密钥以及导入后依然要求导入的解决办法
本文为个人博客备份文章,原文地址: http://validvoid.net/visual-studio-pfx-import/ 导入密钥 在使用 Visual Studio 生产项目时,使用 pfx ...
- 【转】js弹出框、对话框、提示框、弹窗总结
js弹出框.对话框.提示框.弹窗总结 一.js的三种最常见的对话框 //====================== JS最常用三种弹出对话框 ======================== //弹 ...
- 计算Sn
求Sn=a+aa+aaa+…+aa…aaa(有n个a)之值,其中a是一个数字. 例如:2+22+222+2222+22222(n=5), 输入 输入两个数.第一个为a ,第二个为n(表示有多少个数相加 ...
- Python用户交互以及数据类型
一.用户交互与格式化输出 1.用户交互 1.1什么是用户交互 程序等待用户输入的数据,程序执行完毕后为用户反馈信息. 1.2为何程序要与用户交互 为了让计算机像人类一样与用户交互 1.3使用方式 在p ...
- agc001E - BBQ Hard(dp 组合数)
题意 题目链接 Sol 非常妙的一道题目. 首先,我们可以把\(C_{a_i + b_i + a_j + b_j}^{a_i + a_j}\)看做从\((-a_i, -b_i)\)走到\((a_j, ...