使用 dict 文字和 dict 构造函数之间有区别吗? [英] Is there a difference between using a dict literal and a dict constructor?

查看:39
本文介绍了使用 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

这篇关于使用 dict 文字和 dict 构造函数之间有区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆