Python

items() method in dictionary

Click for All Topics

items() method in dictionary - Python

  • This method is used to print all items(key-value pair) of the dictionary.
  • The .items() method doesn’t take any argument and it returns the view object that contains the list of tuple and each tuple contains key-value pair.
  • The time complexity of this method is O(n) where n is the number of items in the dictionary.
  • When we call this method with empty dictionary then it doesn’t give any error.

 

Syntax –

dictionary.items()

 

Parameters –

  • return – returns view object that contains a list of tuples, tuple consist of key-value pair

 

Example –

				
					dct={'even':[2,4,6,8,10],'odd':[1,3,5,7,9]}
items=dct.items()
print(items)

# Output -
# dict_items([('even', [2, 4, 6, 8, 10]), ('odd', [1, 3, 5, 7, 9])])
				
			
  • In the above example, first we create a dictionary with some items and store it in dct variable
  • After creating dictionary call the .items() method with dictionary and find all items of the dictionary store the result in items variable.
  • Finally, print the items on the output screen.

Example – with empty dictionary

				
					my_dict={}
items=my_dict.items()
print("Items:",items)

# Output -
# Items: dict_items([])
				
			

Example –

				
					my_dict={'1':'amit',2:'abhay',3:'aditya',4:'aman'}
items=my_dict.items()

for i , j in items:
	print(i,' ',j)

# Output -
# 1   amit
# 2   abhay
# 3   aditya
# 4   aman