cmap = {'US':'USA','GB':'Great Britain'}
def cxlate(country):
try:
ret = cmap[country]
except:
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
7 回答
要么
要么
所以有两种方法可以创建一个dict:
my_dict = dict()
my_dict = {}
但是在这两个选项中,
{}
比dict()
更有效 . CHECK HERE你可以这样做
知道如何编写预设字典也很有用:
将在python字典中添加值 .
不带参数调用
dict
或者简单地写