使用 python 默认字典与 .get()

Lis*_*isa 2 python dictionary

我想要一本默认为 None 的字典。我有两种实现方法:1)使用collections.defaultdict并将默认值设置为None。 https://docs.python.org/2/library/collections.html

2)使用普通字典但使用.get()来获取值。当key不存在时,默认返回None。

哪种方式更好?

qin*_*zuo 5

defaultdict 将使用比 dict.get() 更多的内存,因为如果没有找到键,defaultdict 将使用该键在包装的 dict 中设置默认值。

另一方面,如果 dict 中没有找到 key,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)
Run Code Online (Sandbox Code Playgroud)

使用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)
Run Code Online (Sandbox Code Playgroud)

defaultdict 需要一个可调用的值作为 dict 默认值,您也可以根据需要使用函数或 lambda 自定义您自己的默认值

dict.get($key, $default) 更容易获取每条记录的默认值

谢谢