The items() method of the dictionary class

The items() method retrieves all the items i.e, the name-value pairs, of a dictionary as a dict_view instance. The view gets updated as the items of the dict instance change.

Dictionary Updated 19 Nov 2020 1 min read

Method Name

items

Method Signature

items()

Method Overview

  • The items() method returns the key-value pairs of a dictionary as a dict_items instance.
  • As the original dictionary changes e.g., when name-value pairs are added or removed, the changes are reflected in the view.
  • To get only the values present in a dictionary the values() method to be used.

Parameters

None

Return Value

The key-value pairs of the dictionary as a dict_items instance.

Example

python

# Example Python program that gets the name-value pairs of a dictionary

            # as a dict_items

# Create an instance of dict

            d = {"p1":(20,30),

                 "p2":(30, 40),

                 "p3":(40, 20)}

# Get the name-value pairs of the dict instance

            keyValues = d.items()

print("Dictionary view:")

            # Iterate the dict_items and print each item

            for keyValue in keyValues:

                print(keyValue)

# Add a point to the dictionary

            d["p4"] = (50, 10)

print("Dictionary view after a new point is added:")

            for keyValue in keyValues:

                print(keyValue)

Output

Output
Dictionary view:

            ('p1', (20, 30))

            ('p2', (30, 40))

            ('p3', (40, 20))

            Dictionary view after a new point is added:

            ('p1', (20, 30))

            ('p2', (30, 40))

            ('p3', (40, 20))

            ('p4', (50, 10))