Python

keys() method in dictionary

Click for All Topics

keys() method in dictionary - Python

  • This method is used to get all the keys of the dictionary.
  • This method doesn’t take any parameters and returns a view object that contains the list of all keys.
  • The time complexity of this method is O(1).
  • When we call this method with an empty dictionary, it gives no error.
  • You can use it further by type-casting the view object into the list.

 

Syntax –

dictionary.keys()

 

Parameters –

  • return → returns view object that contains the list of keys of the dictionary.

 

Example  1-

				
					student_marks = {'Anurag':90,'Abhay':92,'Aditya':85,'Naveen':88}
print(student_marks.keys())

# Output -
#  dict_keys(['Anurag', 'Abhay', 'Aditya', 'Naveen'])
				
			
  • In the above example, first we create a dictionary with the student names as the key and marks as the values.
  • After that call the .keys() method with the dictionary and print the output on the console.

Example 2-

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

# Output -
# dict_keys(['odd', 'even'])
				
			

Example 3-

				
					d={}
print(d.keys())

# output -
# dict_keys([])
				
			

Example 4- print all keys without using the .keys() method.

				
					dct={'a':1,'b':2,'c':3,'d':4,'e':5}
for i in dct:
	print(i)

# output -
#  a
#  b
#  c
#  d
#  e
				
			
Example 5-
				
					# Creating a dictionary
my_dict = {'red': '#FF0000', 'green': '#00FF00', 'blue': '#0000FF'}

# Using the keys() method to get a view object
keys_view = my_dict.keys()

# Printing the original dictionary
print("Original Dictionary:", my_dict)

# Using the view object to iterate over the keys
print("Keys from the View Object:")
for key in keys_view:
    print(key)

# Output -
# Original Dictionary: {'red': '#FF0000', 'green': '#00FF00', 'blue': '#0000FF'}
# Keys from the View Object:
# red
# green
# blue