使用dict文字和dict构造函数之间有区别吗?
我注意到使用PyCharm,它可以转换 dict文字:
Using PyCharm, I noticed it offers to convert a dict literal:
d = {
'one': '1',
'two': '2',
}
放入 dict构造器:
d = dict(one='1', two='2')
这些不同的方法是否在某些重要方面有所不同?
(在写这个问题时,我注意到使用dict()
似乎不可能指定数字键..d = {1: 'one', 2: 'two'}
是可能的,但是很明显,dict(1='one' ...)
不能.还有其他什么?)
(While writing this question I noticed that using dict()
it seems impossible to specify a numeric key .. d = {1: 'one', 2: 'two'}
is possible, but, obviously, dict(1='one' ...)
is not. Anything else?)
我认为您已经指出了最明显的区别.除此之外,
I think you have pointed out the most obvious difference. Apart from that,
第一个不需要查找dict
,它应该使它快一点
the first doesn't need to lookup dict
which should make it a tiny bit faster
第二个命令在locals()
中查找dict
,然后在globals()
中查找内置函数,因此您可以通过定义一个名为dict
的局部变量来切换行为,尽管我无法想到这个地方除了可能在调试时之外,将是一个好主意
the second looks up dict
in locals()
and then globals()
and the finds the builtin, so you can switch the behaviour by defining a local called dict
for example although I can't think of anywhere this would be a good idea apart from maybe when debugging