Home » Python

Python Dictionary keys() Method with Example

Python Dictionary keys() Method: Here, we are going to learn how to get the keys of a dictionary as a view object?
Submitted by IncludeHelp, on November 26, 2019

Dictionary keys() Method

keys() method is used to get the all keys as a view object, this view object contains all keys of the dictionary.

Syntax:

    dictionary_name.keys()

Parameter(s):

  • 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:

# Python Dictionary keys() Method with Example

# 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:

# Python Dictionary keys() Method with Example

# 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

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.