【发布时间】:2012-01-15 12:46:52
【问题描述】:
我想用 Python 构建一个字典。但是,我看到的所有示例都是从列表等实例化字典。 ..
如何在 Python 中创建一个新的空字典?
【问题讨论】:
标签: python dictionary
我想用 Python 构建一个字典。但是,我看到的所有示例都是从列表等实例化字典。 ..
如何在 Python 中创建一个新的空字典?
【问题讨论】:
标签: python dictionary
不带参数调用dict
new_dict = dict()
或者直接写
new_dict = {}
【讨论】:
{} 比 dict() 快 4 倍,[] 比 list() 快 5 倍。
你可以这样做
x = {}
x['a'] = 1
【讨论】:
了解如何编写预设字典也很有用:
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
【讨论】:
cxlate 的部分让你的答案看起来太复杂了。我只保留初始化部分。 (cxlate 本身太复杂了,你可以直接return cmap.get(country, '?')。)
KeyError 而不是一个空的 except(这将捕获诸如 KeyboardInterrupt 和 SystemExit 之类的东西)。
>>> dict(a=2,b=4)
{'a': 2, 'b': 4}
将在python字典中添加值。
【讨论】:
d = dict()
或
d = {}
或
import types
d = types.DictType.__new__(types.DictType, (), {})
【讨论】:
types.DictType.__new__(types.DictType, (), {}) 和刚才的{} 有什么区别
【讨论】:
>>> dict.fromkeys(['a','b','c'],[1,2,3])
{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}
【讨论】: