dict【辞書型】・辞書ビュー 3.5 / 3.7~3.10
メソッド 一覧 コンストラクタ 辞書表現 辞書内包表記 繰り返し処理 ソート・最大値・最小値 アンパック 演算子 操作 辞書ビュー
メモ
- 辞書型
- 辞書ビュー
- 辞書のビュー
(詳細は、keys【辞書ビュー取得 (キー)】・values【辞書ビュー取得 (値)】 ・items【辞書ビュー取得 (キー・値)】を参照)
- 辞書のビュー
- 繰り返し処理 (for-in【for ループ】 で処理) 〔 例 〕
対象 メソッド・関数 キー keys【辞書ビュー取得 (キー)】 組み込み関数の reversed【逆順】でキーを逆順に取得 3.8
辞書ビューも対応
reversed(d) は reversed(d.keys()) のショートカット値 values【辞書ビュー取得 (値)】 キー・値 items【辞書ビュー取得 (キー・値)】 - ソート・最大値・最小値
- ソート:組み込み関数 の sorted【ソート】
- キー (値) の最大値:組み込み関数の max【最大値】
- キー (値) の最小値:組み込み関数の min【最小値】
- アンパック〔 例 〕
対象 備考 辞書表現
辞書内包表記ダブルアスタリスク(**)で展開 3.5 関数の引数 ダブルアスタリスク(**)で引数に展開 (複数指定可 3.5 )
キー:引数名 / 値:引数値 - メソッド 一覧
- 演算子〔 例 〕
演算子 備考 dict1 == dict2 要素を比較 (順序は無視) dict1 != dict2 要素を比較 (順序は無視) dict1 is dict2 オブジェクト比較 dict1 is not dict2 オブジェクト比較 dict1 | dict2 3.9 辞書をマージ
(同一キー存在:dict2の値を優先)
〔参考:update【更新】〕dict1 |= other 3.9 辞書等(反復可能なキーと値のペア)とマージして更新
(同一キー存在:otherの値を優先)
〔参考:update【更新】〕【未サポート】
dict1 < dict2
dict1 > dict2
dict1 <= dict2
dict1 >= dict2TypeError 例外 - 操作 〔 例 〕
操作 備考 key in dict 辞書 dict の key (キー) に対応する要素があれば True 、なければ False key not in dict 辞書 dict の key (キー) に対応する要素があれば False 、なければ True dict[key] 辞書 dict の key (キー) に対応する値
存在なし:KeyError 例外 (サブクラスは __missing__(self, key) メソッド呼び出し)dict[key] = value 辞書 dict の key (キー) に対応する値に value を設定
存在なし:挿入
存在あり:上書き
※:setdefault【値 取得 (更新)】は上書きなしdel dict[key] 辞書 dict の key (キー) に対応する要素を削除
存在なし:KeyError 例外
※:get【値 取得】は例外なしiter(dict) 辞書 dict のイテレータ(キー) 取得
iter(dict.keys( )) のショートカットlen(dict) 辞書 dict の要素数 max(dict) 辞書 dict の最大キー (値) min(dict) 辞書 dict の最小キー (値) reversed(dict) 3.8 辞書 dict の逆順イテレータ(キー) 取得
reversed(dict.keys()) のショートカット辞書ビューオブジェクト 操作 備考 x in dictview xに対応する要素があれば True 、なければ False
x は辞書ビューの対象iter(dictview) 辞書ビューのイテレータ(キー) 取得 len(dictview) 辞書ビューの要素数 dictview.mapping 3.10 参照元辞書のラップ (types.MappingProxyType) reversed(dictview) 3.8 辞書ビューの逆順イテレータ 取得
外部リンク
例 (アンパック)
dic1 = {'Key21': 'Value21', 'Key22': 'Value22'}
dic2 = {'Key1': 'Value1', **dic1, 'Key3': 'Value3'}
print(dic2)
# 出力:{'Key1': 'Value1', 'Key21': 'Value21', 'Key22': 'Value22', 'Key3': 'Value3'}
def func(p1, p2, **kwarg):
print(p1, p2, kwarg)
dicP = {'p1': 'Param1', 'p2': 'Param2'}
func(**dicP) # 出力:Param1 Param2 {}
dicP = {'p1': 'Param1', 'p2': 'Param2', 'p3': 'Param3'}
func(**dicP) # 出力:Param1 Param2 {'p3': 'Param3'}
dicP = {'p2': 'Param2', 'p3': 'Param3'}
func("P1", **dicP) # 出力:P1 Param2 {'p3': 'Param3'}
例 (演算子)
# dict1 == dict2
# dict1 != dict2
dic1 = {'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3'}
dic2 = {'Key3': 'Value3', 'Key1': 'Value1', 'Key2': 'Value2'}
dic3 = {'Key1': 'Value1', 'Key2': 'Value20', 'Key3': 'Value3'}
print(dic1 == dic2) # 出力:True
print(dic1 == dic3) # 出力:False
print(dic1 != dic2) # 出力:False
print(dic1 != dic3) # 出力:True
# dict1 is dict2
# dict1 is not dict2
dic1 = {'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3'}
dic2 = {'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3'}
dic3 = dic1
print(dic1 is dic2) # 出力:False
print(dic1 is dic3) # 出力:True
print(dic1 is not dic2) # 出力:True
print(dic1 is not dic3) # 出力:False
# dict1 | dict2
# dict1 |= dict2
dic_1 = {'Key1': 'Value1', 'Key2': 'Value2'}
dic_2 = {'Key3': 'Value3', 'Key4': 'Value4'}
dic_3 = {'Key1': 'VALUE1', 'Key3': 'Value3', 'Key4': 'Value4'}
print(dic_1)
# 出力:{'Key1': 'Value1', 'Key2': 'Value2'}
print(dic_2)
# 出力:{'Key3': 'Value3', 'Key4': 'Value4'}
dic_new = dic_1 | dic_2
print(dic_new)
# 出力:{'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3', 'Key4': 'Value4'}
dic_new = dic_1 | dic_3
print(dic_new)
# 出力:{'Key1': 'VALUE1', 'Key2': 'Value2', 'Key3': 'Value3', 'Key4': 'Value4'}
dic_1 |= dic_2
print(dic_1)
# 出力:{'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3', 'Key4': 'Value4'}
dic_1 |= dic_3
print(dic_1)
# 出力:{'Key1': 'VALUE1', 'Key2': 'Value2', 'Key3': 'Value3', 'Key4': 'Value4'}
lst_1 = [('Key5', 'Value5'), ('Key6', 'Value6')]
lst_2 = [('Key5', 'VALUE5'), ('Key6', 'Value6')]
dic_1 |= lst_1
print(dic_1)
# 出力:{'Key1': 'VALUE1', 'Key2': 'Value2', 'Key3': 'Value3', 'Key4': 'Value4', 'Key5': 'Value5', 'Key6': 'Value6'}
dic_1 |= lst_2
print(dic_1)
# 出力:{'Key1': 'VALUE1', 'Key2': 'Value2', 'Key3': 'Value3', 'Key4': 'Value4', 'Key5': 'VALUE5', 'Key6': 'Value6'}
例 (操作)
dic = {'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3'}
# key in dict
print("Key1" in dic) # 出力:True
print("Key9" in dic) # 出力:False
print("Value1" in dic) # 出力:False
# key not in dict
print("Key1" not in dic) # 出力:False
print("Key9" not in dic) # 出力:True
print("Value1" not in dic) # 出力:True
# dict[key]
dic = {'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3'}
print(dic['Key1']) # 出力:Value1
# print(dic['Key9']) # KeyError 例外
class DictEx(dict):
def __missing__(self, key):
return "Value_" + key
dicEx = DictEx(Key1='Value1', Key2='Value2', Key3='Value3')
print(dicEx)
# 出力:{'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3'}
print(dicEx['Key1']) # 出力:Value1
print(dicEx['Key9']) # 出力:Value_Key9
# dict[key] = value
dic = {'Key1': 'Value1', 'Key2': 'Value2'}
dic['Key1'] = "Value1_New"
dic['Key9'] = "Value9"
print(dic)
# 出力:{'Key1': 'Value1_New', 'Key2': 'Value2', 'Key9': 'Value9'}
# del dict[key]
dic = {'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3'}
del dic['Key2']
print(dic)
# 出力:{'Key1': 'Value1', 'Key3': 'Value3'}
# del dic['Key2'] # KeyError 例外
# iter(dict)
dic = {'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3'}
itr = iter(dic)
for key in itr:
print(key)
# 出力:Key1
# 出力:Key2
# 出力:Key3
# len(dict)
dic = {'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3'}
print(len(dic)) # 出力:3
print(len({})) # 出力:0
# max(dict)
# min(dict)
dic = {'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3'}
print(max(dic)) # 出力:Key3
print(min(dic)) # 出力:Key1
辞書表現
辞書内包表記 3.8
コンストラクタ
メモ
構文
# 辞書表現
{key1:value1[, ...keyN:valueN][,]}
keyNキー
valueN値
※:末尾カンマは無視 (空要素にはならない)
# 辞書内包表記
{key:value [for x in iterable [if 条件式]]+}
keyキーになる式
value値になる式
x (複数:カンマ区切り)iterableから取得した変数 (タプルの場合、複数可)
iterable元になるイテラブル オブジェクト
class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)
kwarg (キーワード引数)追加要素 (キー:引数名 / 値:引数値)
mappingマッピング オブジェクト
iterableイテラブル オブジェクト
例
dic = {'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3'}
print(dic)
# 出力:{'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3'}
dic1 = {'Key21': 'Value21', 'Key22': 'Value22'}
dic2 = {'Key1': 'Value1', **dic1, 'Key3': 'Value3'}
print(dic2)
# 出力:{'Key1': 'Value1', 'Key21': 'Value21', 'Key22': 'Value22', 'Key3': 'Value3'}
dic = {'Key' + str(i): 'Value' + str(i) for i in range(3)}
print(dic)
# 出力:{'Key0': 'Value0', 'Key1': 'Value1', 'Key2': 'Value2'}
dic = {'Key' + str(i): 'Value' + str(i) for i in range(1, 10) if i % 3 == 0}
print(dic)
# 出力:{'Key3': 'Value3', 'Key6': 'Value6', 'Key9': 'Value9'}
lst = ['Key1', 'Key2', 'Key3']
tpl = ('Value1', 'Value2', 'Value3')
dic = {key: value for key, value in zip(lst, tpl)}
print(dic)
# 出力:{'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3'}
dic = {x*10 + y: x*10 + y for x in range(1, 3) for y in range(1, 4)}
print(dic)
# 出力:{11: 11, 12: 12, 13: 13, 21: 21, 22: 22, 23: 23}
dic = {x*10 + y: x*10 + y for x in range(1, 5) if x % 2 == 0 for y in range(3, 9) if y % 3 == 0}
print(dic)
# 出力:{23: 23, 26: 26, 43: 43, 46: 46}
dic = {key: '2 未満' if key < 2 else '2 以上' for key in range(4)}
print(dic)
# 出力:{0: '2 未満', 1: '2 未満', 2: '2 以上', 3: '2 以上'}
lst = [{'Key' + str(x): x + y*10 for x in range(1, 3)} for y in range(1, 4)]
print(lst)
# 出力:[{'Key1': 11, 'Key2': 12}, {'Key1': 21, 'Key2': 22}, {'Key1': 31, 'Key2': 32}]
dic1 = dict(Key1='Value1', Key2='Value2')
print(dic1)
# 出力:{'Key1': 'Value1', 'Key2': 'Value2'}
dic2 = dict(dic1, Key3='Value3')
print(dic2)
# 出力:{'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3'}
tpl = (('Key01', 'Value01'), ('Key02', 'Value02'))
dic3 = dict(tpl, Key03='Value03')
print(dic3)
# 出力:{'Key01': 'Value01', 'Key02': 'Value02', 'Key03': 'Value03'}
# 辞書内包表記 (評価順) Python 3.8
dic = {input("Key? "): input("Value? ") for i in range(2)}
# 入力:Key? KEY1
# 入力:Value? VALUE1
# 入力:Key? KEY2
# 入力:Value? VALUE2
# Python 3.8 以前は不定 (例:CPython は Value? が先)
print(dic)
# 出力:{'KEY1': 'VALUE1', 'KEY2': 'VALUE2'}
clear【全削除】
メモ
- 全ての要素を削除
構文
dict.clear()
戻り値なし
例
dic = {'Key1': 'Value1', 'Key2': 'Value2'}
print(dic) # 出力:{'Key1': 'Value1', 'Key2': 'Value2'}
dic.clear()
print(dic) # 出力:{}
dic.clear()
print(dic) # 出力:{}
copy【浅いコピー】
メモ
- 浅いコピー
構文
dict.copy()
戻り値コピー先の辞書
例
dic = {'Key1': 'Value1', 'Key2': 'Value2'}
dic2 = dic.copy()
print(dic2) # 出力:{'Key1': 'Value1', 'Key2': 'Value2'}
dic2['Key3'] = 'Value3'
print(dic) # 出力:{'Key1': 'Value1', 'Key2': 'Value2'}
print(dic2) # 出力:{'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3'}
lst = ['Value11', 'Value12']
dic3 = {'Key1': lst, 'Key2': 'Value2'}
dic4 = dic3.copy()
print(dic4) # 出力:{'Key1': ['Value11', 'Value12'], 'Key2': 'Value2'}
lst.append("Value13")
print(lst) # 出力:['Value11', 'Value12', 'Value13']
print(dic3) # 出力:{'Key1': ['Value11', 'Value12', 'Value13'], 'Key2': 'Value2'}
print(dic4) # 出力:{'Key1': ['Value11', 'Value12', 'Value13'], 'Key2': 'Value2'}
classmethod fromkeys【辞書生成】
メモ
- キーを元に辞書を生成
- 値は一意
構文
クラスメソッド
dict.fromkeys(iterable[, value])
戻り値生成された辞書
iterableキーを含んだイテラブル オブジェクト
value値 (省略:None)
例
lst = ['key1', 'key2', 'key3']
dic = dict.fromkeys(lst)
print(dic)
# 出力:{'key1': None, 'key2': None, 'key3': None}
tpl = ('key1', 'key2', 'key3')
dic = dict.fromkeys(tpl, "ValueN")
print(dic)
# 出力:{'key1': 'ValueN', 'key2': 'ValueN', 'key3': 'ValueN'}
get【値 取得】
setdefault【値 取得 (更新)】
メモ
- 値 取得
- setdefault【値 取得 (更新)】:存在しない場合は挿入 (既存の要素は更新なし)
構文
dict.get(key[, default])
dict.setdefault(key[, default])
戻り値キーに対応する値 (setdefault:存在しない場合、挿入)
keyキー
defaultキーが存在しない場合の値 (省略:None)
例
dic = {'Key1': 'Value1', 'Key2': 'Value2'}
value = dic.get("Key1")
print(value) # 出力:Value1
print(dic)
# 出力:{'Key1': 'Value1', 'Key2': 'Value2'}
value = dic.get("Key9")
print(value) # 出力:None
print(dic)
# 出力:{'Key1': 'Value1', 'Key2': 'Value2'}
value = dic.get("Key1", "Default")
print(value) # 出力:Value1
print(dic)
# 出力:{'Key1': 'Value1', 'Key2': 'Value2'}
value = dic.get("Key99", "Default")
print(value) # 出力:Default
print(dic)
# 出力:{'Key1': 'Value1', 'Key2': 'Value2'}
dic = {'Key1': 'Value1', 'Key2': 'Value2'}
value = dic.setdefault("Key1")
print(value) # 出力:Value1
print(dic)
# 出力:{'Key1': 'Value1', 'Key2': 'Value2'}
value = dic.setdefault("Key9")
print(value) # 出力:None
print(dic)
# 出力:{'Key1': 'Value1', 'Key2': 'Value2', 'Key9': None}
value = dic.setdefault("Key1", "Default")
print(value) # 出力:Value1
print(dic)
# 出力:{'Key1': 'Value1', 'Key2': 'Value2', 'Key9': None}
value = dic.setdefault("Key99", "Default")
print(value) # 出力:Default
print(dic)
# 出力:{'Key1': 'Value1', 'Key2': 'Value2', 'Key9': None, 'Key99': 'Default'}
keys【辞書ビュー取得 (キー)】
values【辞書ビュー取得 (値)】
items【辞書ビュー取得 (キー・値)】
dictview.mapping【参照元辞書ラップ】 3.10
メモ
- 辞書ビューを取得
対象 メソッド キー keys【辞書ビュー取得 (キー)】 値 values【辞書ビュー取得 (値)】 キー・値 items【辞書ビュー取得 (キー・値)】 - for-in【for ループ】 で繰り返し処理
items() ではタプルのアンパックで個別の変数に代入可 (tuple【タプル型】のパック・アンパック 参照) - dictview.mapping【参照元辞書ラップ】で参照元辞書の参照
- for-in【for ループ】 で繰り返し処理
- 辞書の変更で、辞書ビューも変更
- reversed【逆順】関数で逆順 3.8
構文
dict.keys()
dict.values()
dict.items()
戻り値対応する辞書ビュー
dictview.mapping 3.10
参照参照元辞書のラップ (更新不可:types.MappingProxyType)
例
dic = {'Key1': 'Value1', 'Key2': 'Value2'}
view1 = dic.keys()
view2 = dic.values()
view3 = dic.items()
print(view1.mapping)
# 出力:{'Key1': 'Value1', 'Key2': 'Value2'}
print(view2.mapping)
# 出力:{'Key1': 'Value1', 'Key2': 'Value2'}
print(view3.mapping)
# 出力:{'Key1': 'Value1', 'Key2': 'Value2'}
dic.update(Key3="Value3_New", Key2="Value2_Update")
for key in view1:
print(key)
# 出力:Key1
# 出力:Key2
# 出力:Key3
for value in view2:
print(value)
# 出力:Value1
# 出力:Value2_Update
# 出力:Value3_New
for key, value in view3:
print(key, value)
# 出力:Key1 Value1
# 出力:Key2 Value2_Update
# 出力:Key3 Value3_New
print(view1.mapping)
# 出力:{'Key1': 'Value1', 'Key2': 'Value2_Update', 'Key3': 'Value3_New'}
print(view2.mapping)
# 出力:{'Key1': 'Value1', 'Key2': 'Value2_Update', 'Key3': 'Value3_New'}
print(view3.mapping)
# 出力:{'Key1': 'Value1', 'Key2': 'Value2_Update', 'Key3': 'Value3_New'}
mapping = view3.mapping
for key, value in mapping.items():
print(key, value)
# 出力:Key1 Value1
# 出力:Key2 Value2_Update
# 出力:Key3 Value3_New
# mapping.update(Key4='Value4') # AttributeError
例 (繰り返し処理)
dic = {'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3'}
for key in dic.keys():
print(key)
# 出力:Key1
# 出力:Key2
# 出力:Key3
# Python 3.8
for key in reversed(dic):
print(key)
# 出力:Key3
# 出力:Key2
# 出力:Key1
# Python 3.8
for key in reversed(dic.keys()):
print(key)
# 出力:Key3
# 出力:Key2
# 出力:Key1
dic = {'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3'}
for value in dic.values():
print(value)
# 出力:Value1
# 出力:Value2
# 出力:Value3
# Python 3.8
for value in reversed(dic.values()):
print(value)
# 出力:Value3
# 出力:Value2
# 出力:Value1
dic = {'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3'}
for key, value in dic.items():
print(key, value)
# 出力:Key1 Value1
# 出力:Key2 Value2
# 出力:Key3 Value3
# Python 3.8
for key, value in reversed(dic.items()):
print(key, value)
# 出力:Key3 Value3
# 出力:Key2 Value2
# 出力:Key1 Value1
pop【値 取得 (削除)】
popitem【キー・値 取得 (削除)】3.7
メモ
- 要素を取り出し、辞書から削除
構文
dict.pop(key[, default])
戻り値対応する値 (辞書から削除)
keyキー
defaultkey に対応する値がない場合の値
例外KeyError 例外 (key に対応する値がなく、default が未指定)
dict.popitem()
戻り値(キー, 値) のタプル (辞書から削除)
LIFO のタプル 3.7
任意のタプル 3.0
例外KeyError 例外 (空の辞書)
例
dic = {'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3'}
print(dic)
# 出力:{'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3'}
value = dic.pop("Key1")
print(value) # 出力:Value1
print(dic) # 出力:{'Key2': 'Value2', 'Key3': 'Value3'}
value = dic.pop("Key2", "Default")
print(value) # 出力:Value2
print(dic) # 出力:{'Key3': 'Value3'}
value = dic.pop("Key2", "Default")
print(value) # 出力:Default
print(dic) # 出力:{'Key3': 'Value3'}
# value = dic.pop("Key2") # KeyError 例外
dic = {'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3'}
print(dic)
# 出力:{'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3'}
tpl = dic.popitem()
print(tpl) # 出力:('Key3', 'Value3')
print(dic) # 出力:{'Key1': 'Value1', 'Key2': 'Value2'}
del dic['Key1']
dic['Key1'] = "Value1_New"
print(dic) # 出力:{'Key2': 'Value2', 'Key1': 'Value1_New'}
tpl = dic.popitem()
print(tpl) # 出力:('Key1', 'Value1_New')
print(dic) # 出力:{'Key2': 'Value2'}
tpl = dic.popitem()
print(tpl) # 出力:('Key2', 'Value2')
print(dic) # 出力:{}
# tpl = dic.popitem() # KeyError 例外
update【更新】
メモ
- 辞書を更新 (マージ)
- 重複キーは値を上書き
- 演算子( |【マージ】・|=【マージ更新】) 参照
構文
dict.update(other)
dict.update(key1=value1, ...keyN=valueN)
戻り値なし
other各種形式
dict【辞書型】
キー と 値 が対になったイテラブル
keyNキー
valueN値
例
dic = {'K_1': 'V_1', 'K_X': 'V_X'}
print(dic)
# 出力:{'K_1': 'V_1', 'K_X': 'V_X'}
dic2 = {'K_D': 'V_D', 'K_X': 'V_D'}
dic.update(dic2)
print(dic)
# 出力:{'K_1': 'V_1', 'K_X': 'V_D', 'K_D': 'V_D'}
lst = [['K_L', 'V_L'], ('K_X', 'V_L')]
dic.update(lst)
print(dic)
# 出力:{'K_1': 'V_1', 'K_X': 'V_L', 'K_D': 'V_D', 'K_L': 'V_L'}
tpl = (['K_T', 'V_T'], ('K_X', 'V_T'))
dic.update(tpl)
print(dic)
# 出力:{'K_1': 'V_1', 'K_X': 'V_T', 'K_D': 'V_D', 'K_L': 'V_L', 'K_T': 'V_T'}
dic.update(K_K='V_K', K_X='V_K')
print(dic)
# 出力:{'K_1': 'V_1', 'K_X': 'V_K', 'K_D': 'V_D', 'K_L': 'V_L', 'K_T': 'V_T', 'K_K': 'V_K'}