Der Schlüssel() Methode in Python-Wörterbuch , gibt ein Ansichtsobjekt zurück, das eine Liste aller Schlüssel im Wörterbuch in der Reihenfolge ihrer Einfügung mit Python anzeigt.
Syntax: dict.keys()
Parameter: Es gibt keine Parameter.
Kehrt zurück: Es wird ein Ansichtsobjekt zurückgegeben, das alle Schlüssel anzeigt. Dieses Ansichtsobjekt ändert sich entsprechend den Änderungen im Wörterbuch.
Methode 1: Zugriff auf den Schlüssel mit der Methode „keys()“.
Ein einfaches Beispiel, um zu zeigen, wie die Funktion „keys()“ im Wörterbuch funktioniert.
Python3
wie man einen String in ein Zeichen umwandelt
# Dictionary with three keys> Dictionary1> => {> 'A'> :> 'Geeks'> ,> 'B'> :> 'For'> ,> 'C'> :> 'Geeks'> }> # Printing keys of dictionary> print> (Dictionary1.keys())> |
>
>
Ausgabe:
dict_keys(['A', 'B', 'C'])>
Methode 2: Python-Zugriff auf das Wörterbuch per Schlüssel
Demonstration der praktischen Anwendung von „keys()“ mithilfe von Python-Schleife .
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> |
>
Stellvertretender Polizeikommissar
>
Ausgabe:
2nd key using loop : for TypeError: 'dict_keys' object does not support indexing>
Zeitkomplexität: O(n)
Hilfsraum: O(n)
Notiz: Der zweite Ansatz würde nicht funktionieren, weil dict_keys in Python 3 unterstützen keine Indizierung.
Methode 3: Zugriff auf den Schlüssel mithilfe der Indizierung von „keys()“.
Hier haben wir zunächst alle Schlüssel extrahiert und sie dann implizit in die Python-Liste konvertiert, um von dort aus auf das Element zuzugreifen.
Python3
Java nicht
# 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> ])> |
>
Baudrate in Arduino
>
Ausgabe:
2nd key using keys() : for>
Methode 4: Funktion update() des Python-Wörterbuchs
Um zu zeigen, wie die Wörterbuchschlüssel mithilfe von aktualisiert werden update()-Funktion . Wenn das Wörterbuch aktualisiert wird, werden hier auch die Schlüssel automatisch aktualisiert, um die Änderungen anzuzeigen.
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)> |
>
>
Ausgabe:
Keys before Dictionary Updation: dict_keys(['B', 'A']) After dictionary is updated: dict_keys(['B', 'A', 'C'])>