我想用Python建立一个字典。然而,我所看到的所有例子都是从一个列表实例化一个字典等等。
如何在Python中创建一个新的空字典?
我想用Python建立一个字典。然而,我所看到的所有例子都是从一个列表实例化一个字典等等。
如何在Python中创建一个新的空字典?
当前回答
d = dict()
or
d = {}
or
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
你可以这样做
x = {}
x['a'] = 1
我还没有足够的声誉来评论,所以我分享这个作为答案。
@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/
所以有两种方法来创建字典:
My_dict = dict() My_dict = {}
但在这两个选项中,{}比dict()加上它的可读性更有效。 检查在这里
>>> dict.fromkeys(['a','b','c'],[1,2,3])
{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}