在Python中创build一个新的字典

我想在Python中build立一个字典。 但是,我所看到的所有例子都是从列表中实例化一个字典,等等。 ..

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

调用没有参数的dict

 new_dict = dict() 

或者干脆写

 new_dict = {} 

你可以这样做

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

了解如何编写预设字典对于了解以下内容也很有用:

 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 
 d = dict() 

要么

 d = {} 

要么

 import types d = types.DictType.__new__(types.DictType, (), {}) 
 >>> dict(a=2,b=4) {'a': 2, 'b': 4} 

将在python字典中添加值。