dict()和{}有什么区别? [英] What's the difference between dict() and {}?

查看:412
本文介绍了dict()和{}有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,假设我想制作一本字典.我们将其称为d.但是有多种方法可以在Python中初始化字典!例如,我可以这样做:

So let's say I wanna make a dictionary. We'll call it d. But there are multiple ways to initialize a dictionary in Python! For example, I could do this:

d = {'hash': 'bang', 'slash': 'dot'}

或者我可以这样做:

d = dict(hash='bang', slash='dot')

或者奇怪的是:

d = dict({'hash': 'bang', 'slash': 'dot'})

或者这个:

d = dict([['hash', 'bang'], ['slash', 'dot']])

dict()函数的其他多种方式.因此,显然dict()提供的一件事是语法和初始化的灵活性.但这不是我要问的.

And a whole other multitude of ways with the dict() function. So obviously one of the things dict() provides is flexibility in syntax and initialization. But that's not what I'm asking about.

说我要使d只是一个空字典.当我执行d = {}d = dict()相对时,Python解释器的幕后发生了什么?是做同一件事的两种简单方法吗?使用{}是否具有附加调用?一个系统是否比另一个系统具有更多(甚至可以忽略)的开销?虽然这个问题确实完全不重要,但我很想回答这个问题.

Say I were to make d just an empty dictionary. What goes on behind the scenes of the Python interpreter when I do d = {} versus d = dict()? Is it simply two ways to do the same thing? Does using {} have the additional call of dict()? Does one have (even negligible) more overhead than the other? While the question is really completely unimportant, it's a curiosity I would love to have answered.

推荐答案

>>> def f():
...     return {'a' : 1, 'b' : 2}
... 
>>> def g():
...     return dict(a=1, b=2)
... 
>>> g()
{'a': 1, 'b': 2}
>>> f()
{'a': 1, 'b': 2}
>>> import dis
>>> dis.dis(f)
  2           0 BUILD_MAP                0
              3 DUP_TOP             
              4 LOAD_CONST               1 ('a')
              7 LOAD_CONST               2 (1)
             10 ROT_THREE           
             11 STORE_SUBSCR        
             12 DUP_TOP             
             13 LOAD_CONST               3 ('b')
             16 LOAD_CONST               4 (2)
             19 ROT_THREE           
             20 STORE_SUBSCR        
             21 RETURN_VALUE        
>>> dis.dis(g)
  2           0 LOAD_GLOBAL              0 (dict)
              3 LOAD_CONST               1 ('a')
              6 LOAD_CONST               2 (1)
              9 LOAD_CONST               3 ('b')
             12 LOAD_CONST               4 (2)
             15 CALL_FUNCTION          512
             18 RETURN_VALUE        

dict()显然是C内置的.一个真正聪明或专心的人(不是我)可以查看口译员的资料并告诉您更多信息.我只是想炫耀dis.dis. :)

dict() is apparently some C built-in. A really smart or dedicated person (not me) could look at the interpreter source and tell you more. I just wanted to show off dis.dis. :)

这篇关于dict()和{}有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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