Thursday, 23 March 2017

python - Is there a difference between using a dict literal and a dict constructor?



Using PyCharm, I noticed it offers to convert a dict literal:




d = {
'one': '1',
'two': '2',
}




into a dict constructor:




d = dict(one='1', two='2')




Do these different approaches differ in some significant way?



(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?)


Answer




I think you have pointed out the most obvious difference. Apart from that,



the first doesn't need to lookup dict which should make it a tiny bit faster



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


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...