我想用Python建立一个字典。然而,我所看到的所有例子都是从一个列表实例化一个字典等等。

如何在Python中创建一个新的空字典?


当前回答

我还没有足够的声誉来评论,所以我分享这个作为答案。

@David Wheaton在他的评论中分享的接受答案的链接不再有效,因为Doug Hellmann已经迁移了他的网站(来源:https://doughellmann.com/posts/wordpress-to-hugo/)。

这是关于“在CPython 2.7中使用dict()而不是{}对性能的影响”的更新链接:https://doughellmann.com/posts/the-performance-impact-of-using-dict-instead-of-in-cpython-2-7-2/

其他回答

>>> dict(a=2,b=4)
{'a': 2, 'b': 4}

将在python字典中添加该值。

你可以这样做

x = {}
x['a'] = 1

不带参数调用dict

new_dict = dict()

或者简单地写

new_dict = {}

所以有两种方法来创建字典:

My_dict = dict() My_dict = {}

但在这两个选项中,{}比dict()加上它的可读性更有效。 检查在这里

d = dict()

or

d = {}

or

import types
d = types.DictType.__new__(types.DictType, (), {})