在Python中创建一个新的字典

我想用Python构建一本字典。 然而,我看到的所有例子都是从列表中实例化一个字典等。 ..

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


调用没有参数的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
链接地址: http://www.djcxy.com/p/53145.html

上一篇: Creating a new dict in Python

下一篇: Is there any difference between cpython and python