我想用Python构建一个字典。但是,我看到的所有示例都是从列表中实例化字典等。 ..
如何在Python中创建一个新的空字典?
答案 0 :(得分:561)
使用无参数调用dict
new_dict = dict()
或简单地写
new_dict = {}
答案 1 :(得分:203)
你可以这样做
x = {}
x['a'] = 1
答案 2 :(得分:22)
知道如何编写预设字典也很有用:
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
答案 3 :(得分:15)
>>> dict(a=2,b=4)
{'a': 2, 'b': 4}
将在python词典中添加值。
答案 4 :(得分:14)
d = dict()
或
d = {}
或
import types
d = types.DictType.__new__(types.DictType, (), {})
答案 5 :(得分:4)
答案 6 :(得分:2)
>>> dict.fromkeys(['a','b','c'],[1,2,3])
{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}