Python Dictionary items() Method

Returns a list of key-value pairs in a dictionary

Usage

The items() method returns a list of tuples containing the key:value pairs of the dictionary.

The first item in each tuple is the key, and the second item is its associated value.

Syntax

dictionary.items()

Examples

Example: Print all items from the dictionary

D = {'name': 'Bob', 'age': 25}
L = D.items()
print(L)	# dict_items([('age', 25), ('name', 'Bob')])

items() method is generally used to iterate through both keys and values of a dictionary.

The return value is the tuples of (key, value).

Example: Iterate through both keys and values of a dictionary

D = {'name': 'Bob', 'age': 25}
for x in D.items():
    print(x)    # ('age', 25) ('name', 'Bob')

items() Returns View Object

The object returned by items() is a view object.

It provides a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes.

Example: View object reflects any changes done to the dictionary

D = {'name': 'Bob', 'age': 25}

# Assign dict items to L
L = D.items()

# modify dict D
D['name'] = 'xx'

# L reflects changes done to dict D
print(L)	# dict_items([('age', 25), ('name', 'xx')])