The preferred syntax for initializing a dictionary

dict(a=’b’) 和 {“a”: “b”} 这两个写法哪种更好, 看到了Stack Overflow 上的讨论, 准备做个实验。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import time


def test_a():
a = {
'a': 'value',
'another': 'value',
}
a['a']



def test_b():
b = dict(
a='value',
another='value',
)
b['a']

def profile(func, num=100000):
start = time.clock()
for x in xrange(num):
func()
end = time.clock()
print '%s cost %.7f' % (func.__name__, end - start)


profile(test_a)
profile(test_b)
test_a cost 0.0232350
test_b cost 0.0378380

结论是性能差距没有那么大,{} 的方式时间会稍微短一点。

但是在 key 的灵活度上,{} 就有很多优势了,比如:

  • key 是 Python 里面的关键字 {“import”: True}
  • key 带有特殊字符,比如 {‘a=b’: True}

这篇文章从更深的层次去分析了这里的原因,推荐阅读: https://doughellmann.com/blog/2012/11/12/the-performance-impact-of-using-dict-instead-of-in-cpython-2-7-2/

关于头图

拍摄自北京动物园

房思琪的初恋乐园
compare and with all