Python Dictionary items()

In this tutorial, we will learn about the Python Dictionary items() method with the help of examples.

The items() method returns a view object that displays a list of dictionary’s (key, value) tuple pairs.

Example

1
2
3
4
5
6
marks = {'Physics':67, 'Maths':87}
 
print(marks.items())
 
 
# Output: dict_items([('Physics', 67), ('Maths', 87)])

1. Syntax of Dictionary items()

The syntax of items() method is:

1
dictionary.items()

Noteitems() method is similar to dictionary’s viewitems() method in Python 2.7.

2. items() Parameters

The items() method doesn’t take any parameters.

3. Return value from items()

The items() method returns a view object that displays a list of a given dictionary’s (key, value) tuple pair.

4. Example 1: Get all items of a dictionary with items()

1
2
3
4
# random sales dictionary
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
 
print(sales.items())

Output

1
dict_items([('apple', 2), ('orange', 3), ('grapes', 4)])

5. Example 2: How items() works when a dictionary is modified?

1
2
3
4
5
6
7
8
9
10
11
# random sales dictionary
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
 
items = sales.items()
 
print('Original items:', items)
 
# delete an item from dictionary
del[sales['apple']]
 
print('Updated items:', items)

Output

1
2
Original items: dict_items([('apple', 2), ('orange', 3), ('grapes', 4)])
Updated items: dict_items([('orange', 3), ('grapes', 4)])

The view object items doesn’t itself return a list of sales items but it returns a view of sales‘s (key, value) pair.

If the list is updated at any time, the changes are reflected on the view object itself, as shown in the above program.