Python dictionary items() Method



The Python dictionary items method returns a view object of the dictionary. The view object consists of the key-value pairs of the dictionary, as a list of tuples.

When the dictionary is changed, the view object also gets changed. Since the items in the dictionary are unordered and mutable, they can be changed, added, and removed after the dictionary is created. However, the items cannot be duplicated within the same dictionary.

Any data type, including numbers and characters like floats, integers, strings, Boolean types etc., can be used for the items in the dictionary. The items() method is generally used to iterate through a dictionary.

Syntax

Following is the syntax of the Python dictionary items() method −

dict.items()

Parameters

This method does not accept any parameter.

Return Value

This method returns a list of tuple pairs of the dictionary.

Example

The following example shows the usage of Python dictionary items() method. Here a dictionary 'dict' is created with the keys: 'Name' and 'Age' and their corresponding values: 'Zara' and '7'. Then the items of the dictionary is retrieved using the items() method.

# Creating a dictionary
dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" %  dict.items())

When we run above program, it produces following result −

Value : dict_items([('Name', 'Zara'), ('Age', 7)])

Example

In here, the value of the key 'RollNo' in the dictionary is changed. The new specified value is '37'. Therefore, when we change the value of an item in the dictionary, the view object is also changed and gets updated:

# Creating a dictionary
dict_1 = {'Name': 'Rahul', 'RollNo': 43, 'Sex':'Male'}
res = dict_1.items()
print ("The dictionary is: ", res )
dict_1['RollNo'] = 37
print ("The dictionary view-object is: ", res)

While executing the above code we get the following output −

The dictionary is:  dict_items([('Name', 'Rahul'), ('RollNo', 43), ('Sex', 'Male')])
The dictionary view-object is:  dict_items([('Name', 'Rahul'), ('RollNo', 37), ('Sex', 'Male')])

Example

The items() method does not raise any error if an empty dictionary is called on this method. It returns an empty dictionary.

# Creating an empty dictionary  
Animal = {} 
# Invoking the method  
res = Animal.items()  
# Printing the result  
print('The dictionary is: ', res)  

Following is an output of the above code −

The dictionary is:  dict_items([])

Example

The items() method is generally used to iterate through a dictionary's keys and values. The tuple of the (key,value) pair is returned using the items() method as shown below:

# Creating a dictionary
dict_1 = {'Animal': 'Lion', 'Order': 'Carnivora', 'Kingdom':'Animalia'}
# Iterating through the dictionary
for res in dict_1.items():
    print(res)

Output of the above code is as follows −

('Animal', 'Lion')
('Order', 'Carnivora')
('Kingdom', 'Animalia')
python_dictionary.htm
Advertisements