×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Python Dictionary keys() Method

By IncludeHelp Last updated : December 21, 2024

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 ↻


Advertisement
Advertisement



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