回答:
dict
パラメータなしで呼び出す
new_dict = dict()
または単に書く
new_dict = {}
{}
超えるdict()
ためと5倍[]
以上list()
。
プリセット辞書の書き方を知ることも知っていると役に立ちます:
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
(KeyboardInterrupt
やのようなものをキャッチするSystemExit
)例外を除いて明示的にをキャッチする必要があります。
>>> dict(a=2,b=4)
{'a': 2, 'b': 4}
Python辞書に値を追加します。
d = dict()
または
d = {}
または
import types
d = types.DictType.__new__(types.DictType, (), {})
したがって、dictを作成するには2つの方法があります。
my_dict = dict()
my_dict = {}
ただし、これらの2つのオプションのうち、読み取り可能{}
なものよりも効率的ですdict()
。
ここで確認
>>> dict.fromkeys(['a','b','c'],[1,2,3])
{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}