在Python中创建一个新字典

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

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

847638 次浏览

你可以这样做

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

调用不带参数的dict

new_dict = dict()

或者简单地写

new_dict = {}
d = dict()

d = {}

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

知道如何编写预先设定的字典也很有用:

cmap =  {'US':'USA','GB':'Great Britain'}


# Explicitly:
# -----------
def cxlate(country):
try:
ret = cmap[country]
except KeyError:
ret = '?'
return ret


present = 'US' # this one is in the dict
missing = 'RU' # this one is not


print cxlate(present) # == USA
print cxlate(missing) # == ?


# or, much more simply as suggested below:


print cmap.get(present,'?') # == USA
print cmap.get(missing,'?') # == ?


# with country codes, you might prefer to return the original on failure:


print cmap.get(present,present) # == USA
print cmap.get(missing,missing) # == RU
>>> dict(a=2,b=4)
{'a': 2, 'b': 4}

将在python字典中添加该值。

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

  1. < p > # EYZ0

  2. < p > # EYZ0

但是在这两个选项中,{}dict()加上它的可读性更有效。 # EYZ0 < / p >
>>> dict.fromkeys(['a','b','c'],[1,2,3])




{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}

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

@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/