De nycklar() metod i Python ordbok , returnerar ett vyobjekt som visar en lista över alla nycklar i ordboken i infogningsordning med Python.
Syntax: dict.keys()
Parametrar: Det finns inga parametrar.
Returnerar: Ett vyobjekt returneras som visar alla nycklar. Detta vyobjekt ändras enligt ändringarna i ordboken.
Metod 1: Åtkomst till nyckeln med metoden keys().
Ett enkelt exempel för att visa hur funktionen keys() fungerar i ordboken.
Python3
datum konvertera till sträng
# Dictionary with three keys> Dictionary1>=> {>'A'>:>'Geeks'>,>'B'>:>'For'>,>'C'>:>'Geeks'>}> # Printing keys of dictionary> print>(Dictionary1.keys())> |
>
>
Produktion:
dict_keys(['A', 'B', 'C'])>
Metod 2: Python-åtkomstordbok med nyckel
Att demonstrera den praktiska tillämpningen av nycklar() med hjälp av Python loop .
Python3
pojo
# 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> |
>
>
Produktion:
2nd key using loop : for TypeError: 'dict_keys' object does not support indexing>
Tidskomplexitet: O(n)
Hjälputrymme: O(n)
Notera: Det andra tillvägagångssättet skulle inte fungera eftersom dict_keys i Python 3 stöder inte indexering.
Metod 3: Åtkomst till nyckel med keys()-indexering
Här extraherade vi först alla nycklar och sedan konverterade vi dem implicit till Python-listan för att komma åt elementet från den.
Python3
datorarbete
# 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>])> |
>
>
Produktion:
2nd key using keys() : for>
Metod 4: Python Dictionary update() funktion
För att visa hur man uppdaterar ordboksnycklarna med hjälp av update() funktion . Här, när ordboken uppdateras, uppdateras också nycklar automatiskt för att visa ändringarna.
Python3
tom lista java
# 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)> |
>
>
Produktion:
Keys before Dictionary Updation: dict_keys(['B', 'A']) After dictionary is updated: dict_keys(['B', 'A', 'C'])>