In python, we can view a dictionary’s items as (key, value)
tuple pairs using the dictionary function items()
. In this tutorial, we’ll look at how to use the items()
function along with some examples.
Before we proceed, here’s a quick refresher on dictionaries in python – Dictionaries are a collection of items used for storing key to value mappings. They are mutable and hence we can update the dictionary by adding new key-value pairs, removing existing key-value pairs, or changing the value corresponding to a key. For more, check out our guide on dictionaries and other data structures in python.
The items() function
The dictionary function items()
returns a view object that displays a list of dictionary’s (key, value)
tuple pairs. The following is the syntax:
sample_dict.items()
Here, sample_dict is the dictionary whose items you want to view.
Parameters: The items()
function does not take any parameters.
Highlighted programs for you
Flatiron School
Flatiron School
University of Maryland Global Campus
University of Maryland Global Campus
Creighton University
Creighton University
Returns: It returns a view object of the dictionary’s items as a list of (key, value) tuple pairs. For more on dictionary view objects, refer to the python docs.
Example 1: View items of a python dictionary
# dictionary of a sample portfolio
shares1 = {'APPL': 100, 'GOOG': 50}
shares2 = {}
# print the items of the shares1 and shares2
print("Items of shares1:", shares1.items())
print("Items of shares2:", shares2.items())
Output:
Items of shares1: dict_items([('APPL', 100), ('GOOG', 50)])
Items of shares2: dict_items([])
In the above example, we use the dictionary items()
function to view the items of the dictionaries shares1
and shares2
. For shares1
, the function returns a view object with the list of dictionary items as (key, value) tuple pairs. For the empty dictionary shares2
, it returns a view object with an empty list.
Example 2: When the dictionary is updated
# dictionary of a sample portfolio
shares = {'APPL': 100, 'GOOG': 50}
items = shares.items()
# print the items of the shares
print("Items of shares:", items)
# update the dictionary
shares.update({'TSLA': 80})
# print the items of the shares
print("Items of shares:", items)
Output:
Items of shares: dict_items([('APPL', 100), ('GOOG', 50)])
Items of shares: dict_items([('APPL', 100), ('GOOG', 50), ('TSLA', 80)])
In the above example, we print the items of the dictionary shares
before and after the update. We see that the view object items
gets automatically updated when a change is made to the dictionary. It’s important to note that the items()
function does not return a list of the dictionary’s items rather it returns a dynamic view of the dictionary’s (key, values) pairs.
Note that the dictionary view object can be iterated over and supports membership tests.
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.