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

查看:115
本文介绍了使用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天全站免登陆