'setdefault'dict方法的用例 [英] Use cases for the 'setdefault' dict method
问题描述
在Python 2.5中添加 collections.defaultdict
大大减少了对 dict
的 setdefault
方法。这个问题是为了我们的集体教育:
The addition of collections.defaultdict
in Python 2.5 greatly reduced the need for dict
's setdefault
method. This question is for our collective education:
- 什么是
setdefault
今天在Python 2.6 / 2.7? -
setdefault
的受欢迎的用例取代了collections.defaultdict
?
- What is
setdefault
still useful for, today in Python 2.6/2.7? - What popular use cases of
setdefault
were superseded withcollections.defaultdict
?
推荐答案
你可以说 defaultdict在填写dict 和
对于在填充或填充之后设置默认值很有用dict 。 setdefault
之前设置默认值
You could say defaultdict
is useful for settings defaults before filling the dict and setdefault
is useful for setting defaults while or after filling the dict.
可能是最常见的用例:分组项目(未排序的数据,否则使用 itertools.groupby
)
Probably the most common use case: Grouping items (in unsorted data, else use itertools.groupby
)
# really verbose
new = {}
for (key, value) in data:
if key in new:
new[key].append( value )
else:
new[key] = [value]
# easy with setdefault
new = {}
for (key, value) in data:
group = new.setdefault(key, []) # key might exist already
group.append( value )
# even simpler with defaultdict
new = defaultdict(list)
for (key, value) in data:
new[key].append( value ) # all keys have a default already
有时你想确保具体创建一个dict后存在键。在这种情况下, defaultdict
不起作用,因为它仅在显式访问上创建密钥。认为您使用HTTP-ish与许多标题 - 一些是可选的,但您需要默认值:
Sometimes you want to make sure that specific keys exist after creating a dict. defaultdict
doesn't work in this case, because it only creates keys on explicit access. Think you use something HTTP-ish with many headers -- some are optional, but you want defaults for them:
headers = parse_headers( msg ) # parse the message, get a dict
# now add all the optional headers
for headername, defaultvalue in optional_headers:
headers.setdefault( headername, defaultvalue )
这篇关于'setdefault'dict方法的用例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!