Dictionary keys() method in Python

Spread the love

keys() method –

The keys() method in dictionary returns a list of all the keys in a dictionary.

syntax of keys() method –

dict.keys()

Let’s create a dictionary that contains the prices of shares.

In [1]: prices = {'icici': 710, 'reliance': 2617, 'airtel': 737}

Now, to get all the keys of a dictionary we can use the keys() method.

In [2]: prices.keys()
Out[2]: dict_keys(['icici', 'reliance', 'airtel'])

Looping through all the keys of a dictionary –

You can also loop through all the keys of a dictionary using a for loop.

In [3]: for key in prices.keys():
   ...:     print(key)
   ...:     
icici
reliance
airtel

Rating: 1 out of 5.

Leave a Reply