python 中的 dict() 与 { } 哪个更好? [英] dict() vs { } in python which is better?
本文介绍了python 中的 dict() 与 { } 哪个更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道,在以下两种方法中声明字典的最佳做法是什么?为什么?
I like to know, which is the best practice to declare dictionary in below 2 approaches and why?
>>>a=dict(one=2, two=3) # {"two":3, "one":2}
>>>a={"two":3, "one":2}
推荐答案
你会相信 有人已经分析过(从性能角度).
Would you believe someone has already analyzed that (from a performance perspective).
使用 CPython 2.7,使用 dict() 创建字典最多需要 6时间更长,涉及更多的内存分配操作字面语法.使用 {} 创建字典,特别是如果您是预先填充它们,除非文字语法不适用于您案例.
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.
这篇关于python 中的 dict() 与 { } 哪个更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文