Python Dictionary keys() Method (with Examples)

Python Dictionary keys() Method: In this tutorial, we will learn about the keys() method of a dictionary with its usage, syntax, parameters, return type, and examples. By IncludeHelp Last updated : June 12, 2023

Python Dictionary keys() Method

The keys() is an inbuilt method of dict class that is used to get all keys as a view object, this view object contains all keys of the dictionary. The method is called with this dictionary and returns the dictionary keys as a view object.

Syntax

The following is the syntax of keys() method:

dictionary_name.keys()

Parameter(s):

The following are the parameter(s):

  • None - It does not accept any parameter.

Return Value

The return type of this method is <class 'dict_keys'>, it returns the keys of the dictionary as view object.

Example 1: Use of Dictionary keys() Method

# dictionary declaration
student = {
  "roll_no": 101,
  "name": "Shivang",
  "course": "B.Tech",
  "perc" : 98.5
}

# printing dictionary
print("data of student dictionary...")
print(student)

# printing keys
print("keys of student dictionary...")
print(student.keys())

# printing return type of student.keys() Method
print("return type is: ", type(student.keys()))

Output

data of student dictionary...
{'course': 'B.Tech', 'roll_no': 101, 'perc': 98.5, 'name': 'Shivang'}
keys of student dictionary...
dict_keys(['course', 'roll_no', 'perc', 'name'])
return type is:  <class 'dict_keys'>

If we make any changes in the dictionary, view object will also be reflected, consider the given example,

Example 2: Use of Dictionary keys() Method

# dictionary declaration
student = {
  "roll_no": 101,
  "name": "Shivang",
  "course": "B.Tech",
  "perc" : 98.5
}

# printing dictionary
print("data of student dictionary...")
print(student)

# printing keys
print("keys of student dictionary...")
print(student.keys())

# changing a value
student['roll_no'] = 999

# printing dictionary
print("data of student dictionary after update...")
print(student)

Output

data of student dictionary...
{'course': 'B.Tech', 'roll_no': 101, 'perc': 98.5, 'name': 'Shivang'}
keys of student dictionary...
dict_keys(['course', 'roll_no', 'perc', 'name'])
data of student dictionary after update...
{'course': 'B.Tech', 'roll_no': 999, 'perc': 98.5, 'name': 'Shivang'}

See the output, value of roll_no is changed.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.