English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Fonction en Python

Types de données en Python

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Python Knowledge

Python Reference Manual

Python dictionary items() usage and examples

Python dictionary methods

The items() method returns a view object that displays a list of (key, value) tuples of the dictionary.

The syntax of the items() method is:

dictionary.items()

The items() method is similar to Python 2.7in the dictionary viewitems() method

items() parameters

The items() method does not take any parameters.

Return values from items()

The items() method returns a list of (key, value) tuple arrays that can be traversed.

Example1: Get all items in the dictionary using items()

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

When running this program, the output is:

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

Example2: How does items() work after modifying the dictionary?

# Random sales dictionary
sales = {'apple': 2, 'orange': 3, 'grapes': 4 }
items = sales.items()
print('Original items:', items)
# Delete an item from the dictionary
del[sales['apple']]
print('Updated items:', items)

When running this program, the output is:

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

The items method of the view object itself does not return a list of sales items, but a view of (key, value) pairs of sales.

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

Python dictionary methods