Dictionary items() method in Python

Spread the love

items() method –

The dictionary items() method returns a view object. A view object contains a list of key-value pair tuples.

Syntax of items() method –

dict.items()

Let’s create a dictionary which contains prices of stocks.

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

Now we can call the items() method to get the list of key-value pairs of the dictionary.

In [2]: prices.items()
Out[2]: dict_items([('icici', 710), ('reliance', 2617), ('airtel', 737)])

Looping through key-value pairs in the dictionary –

We can use a for loop to loop through all the key-value pairs of the dictionary using items() method.


In [3]: for key, value in prices.items():
   ...:     print('\nShare:', key)
   ...:     print('Price:', value)
   ...:     

Share: icici
Price: 710

Share: reliance
Price: 2617

Share: airtel
Price: 737

Rating: 1 out of 5.

Leave a Reply