Mètode de claus del diccionari Python ().

El claus() mètode en Diccionari Python , retorna un objecte de vista que mostra una llista de totes les claus del diccionari per ordre d'inserció mitjançant Python.

Sintaxi: dict.keys()

Paràmetres: No hi ha paràmetres.

Devolucions: Es retorna un objecte de vista que mostra totes les claus. Aquest objecte de vista canvia segons els canvis del diccionari.

Mètode 1: Accés a la clau mitjançant el mètode keys().

Un exemple senzill per mostrar com funciona la funció keys() al diccionari.

Python 3




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

Sortida:

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

Mètode 2: diccionari d'accés Python per clau

Demostració de l'aplicació pràctica de keys() utilitzant el Bucle Python .

Python 3




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

Sortida:

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

Complexitat temporal: O(n)
Espai auxiliar: O(n)

Nota: El segon enfocament no funcionaria perquè dict_keys a Python 3 no admeten la indexació.

Mètode 3: Accés a la clau mitjançant la indexació keys().

Aquí, primer vam extreure totes les claus i després les vam convertir implícitament a la llista de Python per accedir a l'element des d'ella.

Python 3




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

Sortida:

2nd key using keys() : for 

Mètode 4: funció d'actualització del diccionari Python ().

Per mostrar com actualitzar les claus del diccionari amb el funció update(). . Aquí, quan el diccionari s'actualitza, les claus també s'actualitzen automàticament per mostrar els canvis.

Python 3




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

Sortida:

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