我想要一本默认为"无"的字典。 我有两种实现方法:
1)使用collections.defaultdict并将默认值设置为None。
https://docs.python.org/2/library/collections.html
2)使用普通字典,但使用.get()获取值。 当键不存在时,默认情况下它返回None。
哪种方法更好?
尝试以下线程:stackoverflow.com/questions/7423428/
像往常一样,"哪个更好?"的答案 是"取决于"。 这些方法需要权衡。 您需要什么?
defaultdict将比dict.get()使用更多的内存,因为如果找不到键,则defaultdict将使用键在包装好的dict中设置默认值。
另一方面,如果在dict中找不到键,则dict.get()仅直接返回默认值。无需额外空间。
使用python2使用空字典运行2亿,
200000000 199.584 0.000 283.804 0.000 default.py:11(get_default)
200000000 158.268 0.000 158.268 0.000 default.py:14(get_defaultdict)
使用python2使用空字典运行100万个数据时的内存使用情况,
Line # Mem usage Increment Line Contents
================================================
17 10.918 MiB 10.918 MiB @profile
18 def run_get_default():
19 10.918 MiB 0.000 MiB h = {}
20 10.918 MiB 0.000 MiB for i in xrange(0, COUNT):
21 10.918 MiB 0.000 MiB get_default(h, i)
22 10.918 MiB 0.000 MiB get_default(h, i)
Line # Mem usage Increment Line Contents
================================================
24 10.918 MiB 10.918 MiB @profile
25 def run_get_defaultdict():
26 10.918 MiB 0.000 MiB h = defaultdict(int)
27 83.496 MiB 7.273 MiB for i in xrange(0, COUNT):
28 83.496 MiB 58.141 MiB get_defaultdict(h, i)
29 83.496 MiB 7.164 MiB get_defaultdict(h, i)
defaultdict需要一个可调用的值作为dict默认值,您也可以根据需要使用函数或lambda自定义自己的默认值
dict.get($ key,$ default)更容易获得每个记录的默认值
谢谢
如果只希望默认值为"无"。只是使用.get()方法,这不会变得简单。
另外,如果您希望以后将该值设置为"无",则可以使用setdefault方法
a = {}
a[1] ="1"
print(a.get(1)) # prints 1
print(a.get(2)) # prints None
print(a.setdefault(2, None)) # prints None, and now a has an entry with key 2, and a value of None
要使用defaultdict,您需要编写如下内容
from collections import defaultdict
b = defaultdict(lambda: None) # this lambda returns the default value,
# None in this case
b[1] ="1"
print(b[1]) # prints 1
print(b[2]) # prints None
正如qingdaojunzuo在回答中指出的那样,.get()比使用默认字典要快。因此,最好坚持下去。但是,如果您需要返回None以外的其他值,则defaultdict是答案
这不解决defaultdict
哎呀,我有点忘了,谢谢@ juanpa.arrivillaga