The Items Method Of The Dictionary Class

Method Name:

items

Method Signature:

items()

Method Overview:

  • The items() method returns the key-value pairs of the 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.

Parameters:

None

Return Value:

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

Example:

 

# 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:

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))

 


Copyright 2023 © pythontic.com