Cucco’s Compute Hack

コンピュータ関係の記事を書いていきます。

可変引数のテスト**kwargs

可変引数のテスト

プログラム
def func1(**kwargs):
    print(kwargs)
    # キーに一致する値の取得。キーがない場合はNoneになる。
    print(kwargs.get("a"))
    print(kwargs.get("b"))
    print(kwargs.get("c"))
    print(kwargs.get("key1"))
    print(kwargs.get("key2"))
    print(kwargs.get("key3"))


print("func1(key1=1, key2=2)の場合")
func1(key1=1, key2=2)

# 辞書を引数として渡せる
print("func1(**dict1)の場合")
dict1 = {"a": 1, "b": "bb"}
func1(**dict1)
実行結果
func1(key1=1, key2=2)の場合
{'key1': 1, 'key2': 2}
None
None
None
1
2
None
func1(**dict1)の場合
{'a': 1, 'b': 'bb'}
1
bb
None
None
None
None