Answers:
dict
无参数调用
new_dict = dict()
或简单地写
new_dict = {}
{}
over中获得了dict()
5倍的[]
速度list()
。
知道如何编写预设字典对了解也很有帮助:
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
cxlate
会使您的回答显得过于复杂。我只保留初始化部分。(cxlate
本身太复杂了。您可以return cmap.get(country, '?')
。)
KeyError
而不是裸除(它将捕获诸如KeyboardInterrupt
和SystemExit
)。
>>> dict(a=2,b=4)
{'a': 2, 'b': 4}
将值添加到python字典中。
d = dict()
要么
d = {}
要么
import types
d = types.DictType.__new__(types.DictType, (), {})
>>> dict.fromkeys(['a','b','c'],[1,2,3])
{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}