Metodo keys() del dizionario Python

IL chiavi() metodo dentro Dizionario Python , restituisce un oggetto vista che visualizza un elenco di tutte le chiavi nel dizionario in ordine di inserimento utilizzando Python .

Sintassi: dict.keys()

parametri: Non ci sono parametri.

Ritorna: Viene restituito un oggetto vista che visualizza tutte le chiavi. Questo oggetto della vista cambia in base alle modifiche nel dizionario.

Metodo 1: Accesso alla chiave utilizzando il metodo keys()

Un semplice esempio per mostrare come funziona la funzione keys() nel dizionario.

Python3




# Dictionary with three keys> Dictionary1> => {> 'A'> :> 'Geeks'> ,> 'B'> :> 'For'> ,> 'C'> :> 'Geeks'> }> # Printing keys of dictionary> print> (Dictionary1.keys())>

Produzione:

dict_keys(['A', 'B', 'C']) 

Metodo 2: dizionario di accesso Python tramite chiave

Dimostrare l'applicazione pratica di keys() utilizzando il metodo Ciclo di 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>

Produzione:

2nd key using loop : for TypeError: 'dict_keys' object does not support indexing 

Complessità temporale: O(n)
Spazio ausiliario: O(n)

Nota: Il secondo approccio non funzionerebbe perché dict_keys in Python 3 non supportano l'indicizzazione.

Metodo 3: accesso alla chiave utilizzando l'indicizzazione keys()

Qui, abbiamo prima estratto tutte le chiavi e poi le abbiamo convertite implicitamente nella lista Python per accedere all'elemento da essa.

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> ])>

Produzione:

2nd key using keys() : for 

Metodo 4: funzione update() del dizionario Python

Per mostrare come aggiornare le chiavi del dizionario utilizzando il file funzione aggiorna() . Qui, quando il dizionario viene aggiornato, anche le chiavi vengono aggiornate automaticamente per mostrare le modifiche.

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)>

Produzione:

Keys before Dictionary Updation: dict_keys(['B', 'A']) After dictionary is updated: dict_keys(['B', 'A', 'C'])