对于想了解pythondict:获取vssetdefault的读者,本文将是一篇不可错过的文章,我们将详细介绍python获取dict的key和value,并且为您提供关于(转)Python3coll
对于想了解python dict:获取vs setdefault的读者,本文将是一篇不可错过的文章,我们将详细介绍python获取dict的key和value,并且为您提供关于(转)Python 3 collections.defaultdict() 与 dict的使用和区别、14-python基础—python3中的defaultdict()、for 循环、dict.setdefault(key,[]).append(value)、result=defaultdict(list)、Python collections.defaultdict() 与 dict用法示例的有价值信息。
本文目录一览:- python dict:获取vs setdefault(python获取dict的key和value)
- (转)Python 3 collections.defaultdict() 与 dict的使用和区别
- 14-python基础—python3中的defaultdict()
- for 循环、dict.setdefault(key,[]).append(value)、result=defaultdict(list)
- Python collections.defaultdict() 与 dict用法示例
python dict:获取vs setdefault(python获取dict的key和value)
以下两个表达式似乎与我等效。哪一个更好?
data = [(''a'', 1), (''b'', 1), (''b'', 2)]d1 = {}d2 = {}for key, val in data: # variant 1) d1[key] = d1.get(key, []) + [val] # variant 2) d2.setdefault(key, []).append(val)
结果是相同的,但是哪个版本更好或更确切地说是pythonic?
我个人觉得版本2更难理解,对我而言setdefault非常难以掌握。如果我理解正确,它将在字典中查找“键”的值(如果不可用),在字典中输入“
[]”,返回对该值或“ []”的引用,并在该值后附加“ val”参考。虽然肯定很平滑,但至少(至少对我而言)不是直观的。
在我看来,版本1更容易理解(如果可用,请获取“ key”的值,否则请获取“ []”,然后加入由[val]组成的列表并将结果放入“ key”
)。但是,虽然更直观易懂,但我担心此版本的性能会下降,所有这些列表都会创建。另一个缺点是“
d1”在表达式中出现两次,这很容易出错。可能有一个使用get的更好的实现,但是目前我无法理解。
我的猜测是,尽管经验不足的人更难以掌握版本2,但它会更快,因此更可取。意见?
答案1
小编典典你的两个例子做同样的事情,但并不意味着get
与setdefault
做。
两者之间的区别基本上是手动设置d[key]
为每次指向列表,而不是仅在未设置时才setdefault
自动设置d[key]
为列表。
我使这两种方法尽可能相似
from timeit import timeitprint timeit("c = d.get(0, []); c.extend([1]); d[0] = c", "d = {1: []}", number = 1000000)print timeit("c = d.get(1, []); c.extend([1]); d[0] = c", "d = {1: []}", number = 1000000)print timeit("d.setdefault(0, []).extend([1])", "d = {1: []}", number = 1000000)print timeit("d.setdefault(1, []).extend([1])", "d = {1: []}", number = 1000000)
并得到
0.7947233787110.8118822722560.7244292059990.722129751973
因此setdefault
比get
为此目的快10%。
该get
方法可以使您做的事 少于
使用setdefault
。KeyError
即使您不想设置密钥,也可以使用它来避免在密钥不存在时得到提示(如果那会经常发生)。
请参阅“ setdefault”的dict方法的用例,并且dict.get()方法返回一个指针,以获取有关这两种方法的更多信息。
关于主题的setdefault
结论是,大多数情况下,您想使用defaultdict
。关于该线程的get
结论是它很慢,通常最好(在速度方面)使用defaultdict或处理错误(取决于字典的大小和您的用例)进行双重查找。
(转)Python 3 collections.defaultdict() 与 dict的使用和区别
原文:https://www.cnblogs.com/herbert/archive/2013/01/09/2852843.html
在Python里面有一个模块collections,解释是数据类型容器模块。这里面有一个collections.defaultdict()经常被用到。主要说说这个东西。
综述:
这里的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)]

14-python基础—python3中的defaultdict()
1.collections.defaultdict 类
from collections import defaultdict
2.collections.defaultdict 类与工厂函数dict比较:
(1) 众所周知,在Python中如果访问dict字典中不存在的键,会引发KeyError异常。但是有时候,字典中的每个键都存在默认值是非常方便的。defaultdict可以避免KeyError异常。
1 # 1-dict()
2 strings = (''puppy'', ''kitten'', ''puppy'', ''puppy'',
3 ''weasel'', ''puppy'', ''kitten'', ''puppy'')
4 counts = {}
5 for kw in strings:
6 counts[kw] += 1
7
8 # 报错
9 #Traceback (most recent call last):
10 # File "C:\Users\summer\Desktop\demo.py", line 5, in <module>
11 # counts[kw] += 1
12 #KeyError: ''puppy''
13
14 # 2-defaultdict()
15 from collections import defaultdict
16
17 strings = (''puppy'', ''kitten'', ''puppy'', ''puppy'',
18 ''weasel'', ''puppy'', ''kitten'', ''puppy'')
19 counts = defaultdict(int)
20 for kw in strings:
21 counts[kw] += 1
22
23 print(counts)
24
25 # defaultdict(<class ''int''>, {''puppy'': 5, ''kitten'': 2, ''weasel'': 1})
(2)default_factory 接收一个工厂函数作为参数, 例如int str list set等.
defaultdict类的初始化函数接受一个类型作为参数,当所访问的键不存在的时候,可以实例化一个值作为默认值默认值的类型由工厂函数决定。
from collections import defaultdict
dic1 = defaultdict(int)
print(dic1[''a''])
dic2 = defaultdict(list)
print(dic2[''a''])
dic3 = defaultdict(dict)
print(dic3[''a''])
# 0
# []
# {}
(3)返回的是工厂函数的实例,那么就具有了该工厂函数的相应方法。
for 循环、dict.setdefault(key,[]).append(value)、result=defaultdict(list)
运用for 循环处理各种数据
byletter={}
for word in words:
letter=word[0]
if letter in byletter:
byletter[letter].append(word)
else:
byletter[letter]=[word]
byletter
{''a'': [''apple'', ''and''], ''p'': [''pare'', ''peach''], ''b'': [''banana'']}
dict.setdefault(key,[]).append(value)
setdefault是字典对象的一个实例方法,接收两个参数,用法和字典的get方法类似,但是比 get 更强大。 它可以为给字典的key设定一个默认值(如果key不在字典中的时候) get 方法设置的默认值不会改变原字典, 而setdefault设置的默认值会改变原字典的值。
by_letters={}
for word in words:
letter=word[0]
by_letters.setdefault(letter,[]).append(word)
{''a'': [''apple'', ''and''], ''p'': [''pare'', ''peach''], ''b'': [''banana'']}
data=[(''p'',1),(''p'',2),(''p'',3),(''h'',4),(''h'',5),(''h'',6)]
defaultdict是属于collections 模块下的一个工厂函数,用于构建字典对象,接收一个函数(可调用)对象为作为参数。参数返回的类型是什么,key对应value就是什么类型。
results=defaultdict(list)
data=[(''p'',1),(''p'',2),(''p'',3),(''h'',4),(''h'',5),(''h'',6)]
for (key,value) in data:
results[key].append(value)
results
defaultdict(list, {''p'': [1, 2, 3], ''h'': [4, 5, 6]})
Python collections.defaultdict() 与 dict用法示例
对python这个高级语言感兴趣的小伙伴,下面一起跟随小编 jb51.cc的小编两巴掌来看看吧!在Python里面有一个模块collections,解释是数据类型容器模块。这里面有一个collections.defaultdict()经常被用到。主要说说这个东西。
综述:
这里的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()
再看看它的使用:
# @param Python collections.defaultdict() 与 dict的使用和区别
# @author 小编 jb51.cc|512Pic.com
import collections
s = [('yellow',1),('blue',2),('yellow',3),4),('red',1)]
d = collections.defaultdict(list)
for k,v in s:
d[k].append(v)
list(d.items())
# End www.jb51.cc
这里就开始有点明白了,原来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.
看样子这个文档是难以看懂了。直接看示例:
# @param Python collections.defaultdict() 与 dict的使用和区别
# @author 小编 jb51.cc|512Pic.com
import collections
s = [('yellow',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())
# End www.jb51.cc
看看结果
# @param Python collections.defaultdict() 与 dict的使用和区别
# @author 小编 jb51.cc|512Pic.com
list(d.items())
[('blue',[2,4]),[1]),[1,3])]
>>> list(g.items())
[('blue',3])]
>>> list(e.items())
[('blue',3)]
>>> d
defaultdict(<class 'list'>,{'blue': [2,4],'red': [1],'yellow': [1,3]})
>>> g
{'blue': [2,3]}
>>> e
{'blue': 4,'red': 1,'yellow': 3}
>>> d.items()
dict_items([('blue',3])])
>>> d[blue]
[2,4]
>>> d.keys()
dict_keys(['blue','red','yellow'])
>>> d.default_factory
<class 'list'>
>>> d.values()
dict_values([[2,[1],3]])
# End www.jb51.cc
可以看出
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
后面的道理就一样了。
# @param Python collections.defaultdict() 与 dict的使用和区别
# @author 小编 jb51.cc|512Pic.com
>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
... d[k] += 1
...
>>> list(d.items())
[('i',('p',('s',('m',1)]
# End www.jb51.cc
今天关于python dict:获取vs setdefault和python获取dict的key和value的讲解已经结束,谢谢您的阅读,如果想了解更多关于(转)Python 3 collections.defaultdict() 与 dict的使用和区别、14-python基础—python3中的defaultdict()、for 循环、dict.setdefault(key,[]).append(value)、result=defaultdict(list)、Python collections.defaultdict() 与 dict用法示例的相关知识,请在本站搜索。
本文标签: