Creating a new dictionary in Python Creating a new dictionary in Python python python

Creating a new dictionary in Python


Call dict with no parameters

new_dict = dict()

or simply write

new_dict = {}


You can do this

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


Knowing how to write a preset dictionary is useful to know as well:

cmap =  {'US':'USA','GB':'Great Britain'}# Explicitly:# -----------def cxlate(country):    try:        ret = cmap[country]    except KeyError:        ret = '?'    return retpresent = 'US' # this one is in the dictmissing = 'RU' # this one is notprint cxlate(present) # == USAprint cxlate(missing) # == ?# or, much more simply as suggested below:print cmap.get(present,'?') # == USAprint cmap.get(missing,'?') # == ?# with country codes, you might prefer to return the original on failure:print cmap.get(present,present) # == USAprint cmap.get(missing,missing) # == RU