问题:用Python创建新字典
我想用Python建立字典。但是,我看到的所有示例都是从列表中实例化字典等。..
如何在Python中创建一个新的空字典?
回答 0
dict
无参数调用
new_dict = dict()
或简单地写
new_dict = {}
回答 1
你可以这样做
x = {}
x['a'] = 1
回答 2
知道如何编写预设字典对了解也很有帮助:
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
回答 3
>>> dict(a=2,b=4)
{'a': 2, 'b': 4}
将值添加到python字典中。
回答 4
d = dict()
要么
d = {}
要么
import types
d = types.DictType.__new__(types.DictType, (), {})
回答 5
回答 6
>>> dict.fromkeys(['a','b','c'],[1,2,3])
{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。