“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:
- 今天在 Python 2.6/2.7 中
setdefault
仍有什么用? collections.defaultdict
取代了哪些setdefault
的流行用例?
- 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 和 setdefault<之前对设置默认值很有用/code> 可用于填充字典时或之后设置默认值.
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
from collections import defaultdict
new = defaultdict(list)
for (key, value) in data:
new[key].append( value ) # all keys have a default already
有时您想确保在创建字典后特定键存在.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屋!