Creating a new dict in Python

I want to build a dictionary in Python. However, all the examples that I see are instantiating a dictionary from a list, etc . ..

How do I create a new empty dictionary in Python?


Call dict with no parameters

new_dict = dict()

or simply write

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
链接地址: http://www.djcxy.com/p/53146.html

上一篇: 是否需要关闭不参考它们的文件?

下一篇: 在Python中创建一个新的字典