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

Python basic tutorial

Python flow control

Funciones en Python

Tipos de datos en Python

Python file operations

Python objects and classes

Python date and time

Advanced knowledge of Python

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) tuple pairs of the dictionary.

The syntax of the items() method is:

dictionary.items()

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

items() parameters

The items() method does not take any parameters.

Return values from items()

The items() method returns a list of iterable (key, value) tuple arrays as a function.

Example1: Use items() to get all items in the dictionary

# 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 the (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