我想用Python建立一个字典。然而,我所看到的所有例子都是从一个列表实例化一个字典等等。
如何在Python中创建一个新的空字典?
我想用Python建立一个字典。然而,我所看到的所有例子都是从一个列表实例化一个字典等等。
如何在Python中创建一个新的空字典?
当前回答
>>> dict(a=2,b=4)
{'a': 2, 'b': 4}
将在python字典中添加该值。
其他回答
d = dict()
or
d = {}
or
import types
d = types.DictType.__new__(types.DictType, (), {})
所以有两种方法来创建字典:
My_dict = dict() My_dict = {}
但在这两个选项中,{}比dict()加上它的可读性更有效。 检查在这里
不带参数调用dict
new_dict = dict()
或者简单地写
new_dict = {}
知道如何编写预先设定的字典也很有用:
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字典中添加该值。