leo*_*ora 416 python dictionary list
我想用Python构建一个字典.但是,我看到的所有示例都是从列表中实例化字典等...
如何在Python中创建一个新的空字典?
Jan*_*cak 607
dict没有参数调用
new_dict = dict()
Run Code Online (Sandbox Code Playgroud)
或者简单地写
new_dict = {}
Run Code Online (Sandbox Code Playgroud)
TJD*_*TJD 229
你可以这样做
x = {}
x['a'] = 1
Run Code Online (Sandbox Code Playgroud)
fyn*_*yrz 25
知道如何编写预设字典也很有用:
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
Run Code Online (Sandbox Code Playgroud)
Atu*_*ind 17
>>> dict(a=2,b=4)
{'a': 2, 'b': 4}
Run Code Online (Sandbox Code Playgroud)
将在python字典中添加值.
uke*_*ssi 14
d = dict()
Run Code Online (Sandbox Code Playgroud)
要么
d = {}
Run Code Online (Sandbox Code Playgroud)
要么
import types
d = types.DictType.__new__(types.DictType, (), {})
Run Code Online (Sandbox Code Playgroud)
>>> dict.fromkeys(['a','b','c'],[1,2,3])
{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}
Run Code Online (Sandbox Code Playgroud)