の キー() のメソッド Python辞書 は、Python を使用して、辞書内のすべてのキーのリストを挿入順に表示するビュー オブジェクトを返します。
構文: dict.keys()
パラメーター: パラメータはありません。
戻り値: すべてのキーを表示するビュー オブジェクトが返されます。このビュー・オブジェクトは、ディクショナリの変更に従って変更されます。
方法 1: Keys() メソッドを使用してキーにアクセスする
辞書内でのkeys()関数の動作を示す簡単な例です。
Python3
Javaのwhile条件
# Dictionary with three keys> Dictionary1>=> {>'A'>:>'Geeks'>,>'B'>:>'For'>,>'C'>:>'Geeks'>}> # Printing keys of dictionary> print>(Dictionary1.keys())> |
>
abcと数字
>
出力:
dict_keys(['A', 'B', 'C'])>
方法 2: キーによって Python 辞書にアクセスする
を使用して、keys() の実際のアプリケーションをデモンストレーションします。 Python ループ 。
Python3
# initializing dictionary> test_dict>=> {>'geeks'>:>7>,>'for'>:>1>,>'geeks'>:>2>}> # accessing 2nd element using naive method> # using loop> j>=> 0> for> i>in> test_dict:> >if> (j>=>=> 1>):> >print>(>'2nd key using loop : '> +> i)> >j>=> j>+> 1> |
>
>
出力:
2nd key using loop : for TypeError: 'dict_keys' object does not support indexing>
時間計算量: O(n)
補助スペース: O(n)
注記: 2 番目のアプローチは機能しません。 dict_keys Python 3 ではインデックス作成がサポートされていません。
方法 3:keys() インデックスを使用してキーにアクセスする
ここでは、最初にすべてのキーを抽出し、次にそれらを暗黙的に Python リストに変換して、そこから要素にアクセスします。
ネットワークの種類
Python3
# initializing dictionary> test_dict>=> {>'geeks'>:>7>,>'for'>:>1>,>'geeks'>:>2>}> # accessing 2nd element using keys()> print>(>'2nd key using keys() : '>,>list>(test_dict.keys())[>1>])> |
>
insキー
>
出力:
2nd key using keys() : for>
方法 4: Python Dictionary update() 関数
を使用して辞書キーを更新する方法を示すには、 update() 関数 。ここでは、辞書が更新されると、変更を示すためにキーも自動的に更新されます。
Python3
# Dictionary with two keys> Dictionary1>=> {>'A'>:>'Geeks'>,>'B'>:>'For'>}> # Printing keys of dictionary> print>(>'Keys before Dictionary Updation:'>)> keys>=> Dictionary1.keys()> print>(keys)> # adding an element to the dictionary> Dictionary1.update({>'C'>:>'Geeks'>})> print>(>'
After dictionary is updated:'>)> print>(keys)> |
>
>
出力:
Keys before Dictionary Updation: dict_keys(['B', 'A']) After dictionary is updated: dict_keys(['B', 'A', 'C'])>