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

Python basic tutorial

Python flow control

Python Functions

Python Data Types

Python file operation

Python object and class

Python date and time

Python advanced knowledge

Python reference manual

Python dictionary items() usage and example

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.7in the dictionary viewitems() method

items() parameters

The items() method does not take any parameters.

Return value from items()

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

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 the 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 the 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 the list of sales items, but returns 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