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

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


当前回答

>>> dict.fromkeys(['a','b','c'],[1,2,3])


{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}

其他回答

知道如何编写预先设定的字典也很有用:

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

不带参数调用dict

new_dict = dict()

或者简单地写

new_dict = {}
>>> dict.fromkeys(['a','b','c'],[1,2,3])


{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}
>>> dict(a=2,b=4)
{'a': 2, 'b': 4}

将在python字典中添加该值。

你可以这样做

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