“d = dict()”和“d = dict()”之间的差异且“d={}”

发布于 2024-08-30 21:39:13 字数 205 浏览 4 评论 0原文

$ python2.7 -m timeit 'd={}'
10000000 loops, best of 3: 0.0331 usec per loop
$ python2.7 -m timeit 'd=dict()'
1000000 loops, best of 3: 0.19 usec per loop

为什么要使用其中一种而不是另一种?

$ python2.7 -m timeit 'd={}'
10000000 loops, best of 3: 0.0331 usec per loop
$ python2.7 -m timeit 'd=dict()'
1000000 loops, best of 3: 0.19 usec per loop

Why use one over the other?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

神回复 2024-09-06 21:39:14

如果人们(仅)使用 dict() 而不是 (仅) {},通常是因为他们不了解 {}(是一项壮举),或者因为他们认为它更清晰(这是主观的,但不常见。)

有些事情可以用 dict 做,而用 {}collections.defaultdict(dict)。还有一个事实是,您可以使用关键字参数调用 dict,有些人更喜欢这样:

>>> dict(spam=1, ham=2)
{'ham': 2, 'spam': 1}

就我个人而言,我更喜欢 dict 文字语法,因为当您想要使用不是有效标识符的键时,它效果更好

>>> dict(pass=1)
 File "<stdin>", line 1
    dict(pass=1)
        ^
SyntaxError: invalid syntax
>>> dict('ham and eggs'=1)
  File "<stdin>", line 1
SyntaxError: keyword can't be an expression

:(和混合样式只是因为某些键不是有效的标识符,恶心。)

If people use (just) dict() over (just) {}, it's generally because they don't know about {} (which is quite a feat), or because they think it's clearer (which is subjective, but uncommon.)

There are things you can do with dict that you can't do with {}, though, such as pass it to something that expects a callable, like collections.defaultdict(dict). There's also the fact that you can call dict with keyword arguments, which some people prefer:

>>> dict(spam=1, ham=2)
{'ham': 2, 'spam': 1}

Personally, I prefer the dict literal syntax because it works better when you want to use keys that are not valid identifiers:

>>> dict(pass=1)
 File "<stdin>", line 1
    dict(pass=1)
        ^
SyntaxError: invalid syntax
>>> dict('ham and eggs'=1)
  File "<stdin>", line 1
SyntaxError: keyword can't be an expression

(and mixing styles just because some keys are not valid identifiers, yuck.)

后来的我们 2024-09-06 21:39:14

Doug Hellmann 写了一篇详尽的性能差异比较

tl;博士

在 CPython 2.7 中,使用 dict() 创建字典最多需要 6
时间更长并且涉及更多的内存分配操作
字面语法。使用 {} 创建字典,尤其是当您
预填充它们,除非文字语法不适合您
案例。

Doug Hellmann wrote up an exhaustive comparison of the performance difference.

tl;dr

With CPython 2.7, using dict() to create dictionaries takes up to 6
times longer and involves more memory allocation operations than the
literal syntax. Use {} to create dictionaries, especially if you are
pre-populating them, unless the literal syntax does not work for your
case.

口干舌燥 2024-09-06 21:39:14

就像托马斯说的,我使用 dict() 所以我可以指定关键字。特别是如果我手动构建一个用于数据初始化或其他内容的大型字典:能够使用关键字语法可以为每个元素节省两次击键(以及相关的视觉混乱)。

Like Thomas said, I use dict() so I can specify keywords. Especially if I'm manually constructing a large dictionary for data initialization or whatnot: being able to use keyword syntax saves me two keystrokes (and the associated visual clutter) for every element.

韵柒 2024-09-06 21:39:13

我是那些更喜欢单词而不是标点符号的人之一——这就是我选择 Python 而不是 Perl 的原因之一。毕竟,“没有大括号,生活会更好”(一句古老的 Python 座右铭,印在一件 T 恤上,上面有一个微笑的青少年的卡通画;-)(最初是指大括号与缩进进行分组,当然,但是,嘿,大括号就是大括号!-)。

“支付”一些纳秒(为了使用清晰、可读的短单词而不是大括号、方括号之类的东西)通常是可以承受的(这主要是查找内置名称空间的成本,这是您每次访问时都要付出的代价)使用内置类型或函数,并且您可以通过将一些查找提升到循环之外来稍微优化它)。

所以,我通常喜欢用 dict() 代替 {}list(L) 来代替 L[:] 以及 []list()()tuple() code> 等等——只是对可发音代码的一般样式偏好。当我在使用不同风格的现有代码库上工作时,或者当我在新项目中的队友对另一种方式有强烈的偏好时,我当然可以接受这一点(尽管在队友的情况下尝试进行一些传播) ;-)。

I'm one of those who prefers words to punctuation -- it's one of the reasons I've picked Python over Perl, for example. "Life is better without braces" (an old Python motto which went on a T-shirt with a cartoon of a smiling teenager;-), after all (originally intended to refer to braces vs indentation for grouping, of course, but, hey, braces are braces!-).

"Paying" some nanoseconds (for the purpose of using a clear, readable short word instead of braces, brackets and whatnots) is generally affordable (it's mostly the cost of lookups into the built-ins' namespace, a price you pay every time you use a built-in type or function, and you can mildly optimize it back by hoisting some lookups out of loops).

So, I'm generally the one who likes to write dict() for {}, list(L) in lieu of L[:] as well as list() for [], tuple() for (), and so on -- just a general style preference for pronounceable code. When I work on an existing codebase that uses a different style, or when my teammates in a new project have strong preferences the other way, I can accept that, of course (not without attempting a little evangelizing in the case of the teammates, though;-).

落墨 2024-09-06 21:39:13

d=dict() 需要在 中查找locals() 然后 globals()< /code>然后 __builtins__d={} 则不然

d=dict() requires a lookup in locals() then globals() then __builtins__, d={} doesn't

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文