Python dict() 関数
説明
dict()辞書を作成するための関数です。
構文
dict 構文:
class dict(**kwarg) class dict(mapping, **kwarg) class dict(iterable, **kwarg)
パラメータの説明:
- **kwargs -- キーワード引数。
- mapping -- 要素のコンテナ。マッピング型(Mapping Types)は連想コンテナ型であり、オブジェクトとオブジェクトの間のマッピング関係を格納します。
- iterable -- イテラブルオブジェクト。
戻り値
辞書を返します。
例
以下の例は dict の使用方法を示しています。
>>>dict() # 空の辞書を作成
{}
>>> dict(a='a', b='b', t='t') # キーワード引数を渡す
{'a': 'a', 'b': 'b', 't': 't'}
>>> dict(zip(['one', 'two', 'three'], [1, 2, 3])) # マッピング関数方式で辞書を構築
{'three': 3, 'two': 2, 'one': 1}
>>> dict([('one', 1), ('two', 2), ('three', 3)]) # イテラブルオブジェクト方式で辞書を構築
{'three': 3, 'two': 2, 'one': 1}
>>>
キーワード引数のみを使用して辞書を作成
例
numbers = dict(x=5, y=0)
print('numbers =', numbers)
print(type(numbers))
empty = dict()
print('empty =', empty)
print(type(empty))
print('numbers =', numbers)
print(type(numbers))
empty = dict()
print('empty =', empty)
print(type(empty))
上記の例の出力結果は次のとおりです:
numbers = {'y': 0, 'x': 5}
<class 'dict'>
empty = {}
<class 'dict'>
イテラブルオブジェクトを使用して辞書を作成
例
# キーワード引数を設定していない
numbers1 = dict([('x', 5), ('y', -5)])
print('numbers1 =',numbers1)
# キーワード引数を設定
numbers2 = dict([('x', 5), ('y', -5)], z=8)
print('numbers2 =',numbers2)
# zip() でイテラブルオブジェクトを作成
numbers3 = dict(dict(zip(['x', 'y', 'z'], [1, 2, 3])))
print('numbers3 =',numbers3)
numbers1 = dict([('x', 5), ('y', -5)])
print('numbers1 =',numbers1)
# キーワード引数を設定
numbers2 = dict([('x', 5), ('y', -5)], z=8)
print('numbers2 =',numbers2)
# zip() でイテラブルオブジェクトを作成
numbers3 = dict(dict(zip(['x', 'y', 'z'], [1, 2, 3])))
print('numbers3 =',numbers3)
上記の例の出力結果は次のとおりです:
numbers1 = {'y': -5, 'x': 5}
numbers2 = {'z': 8, 'y': -5, 'x': 5}
numbers3 = {'z': 3, 'y': 2, 'x': 1}
マッピングを使用して辞書を作成
マッピング型(Mapping Types)は連想コンテナ型であり、オブジェクトとオブジェクトの間のマッピング関係を格納します。
例
numbers1 = dict({'x': 4, 'y': 5})
print('numbers1 =',numbers1)
# 以下のコードは dict() を使用する必要はありません
numbers2 = {'x': 4, 'y': 5}
print('numbers2 =',numbers2)
# キーワード引数が渡されます
numbers3 = dict({'x': 4, 'y': 5}, z=8)
print('numbers3 =',numbers3)
print('numbers1 =',numbers1)
# 以下のコードは dict() を使用する必要はありません
numbers2 = {'x': 4, 'y': 5}
print('numbers2 =',numbers2)
# キーワード引数が渡されます
numbers3 = dict({'x': 4, 'y': 5}, z=8)
print('numbers3 =',numbers3)
上記の例の出力結果は次のとおりです:
numbers1 = {'x': 4, 'y': 5}
numbers2 = {'x': 4, 'y': 5}
numbers3 = {'x': 4, 'z': 8, 'y': 5}
その他の拡張
Python 組み込み関数