Python Dictionary Keys() Method

Learn via video course
FREE
View all courses
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning

Overview:

In Python Programming, a dictionary holds the mapping of keys and values. Each key is separated from its value by a colon(:). An item has a key and a value is stated as a pair (key : value).

Syntax of Python Dictionary keys()

The syntax of keys() method in Python is as given below:

Where dict is the name of the dictionary.

Parameters of Python Dictionary keys()

The keys() method in Python don't take any parameters.

Return Value of Python Dictionary keys()

keys() method in Python returns a view object that displays all the keys. This view object changes according to the changes in the dictionary.

Example of Python Dictionary keys()

Code:

Output:

What is keys() method in Python?

The Python keys() method is used to retrieve all of the keys from the dictionary. keys() method in Python dictionary returns a list of all the available keys in the dictionary, or an empty list if the dictionary is empty.

The keys in the dictionary must be of an immutable type (string, number, or tuple with immutable elements) and unique, while the values in the dictionary can be of any data type and can repeat.

More Examples

Example 1: To show the working of keys() method in the Dictionary

Code:

Output:

Example 2: To demonstrate how the Dictionary is updated

Code:

Output:

Exaplanation:

First, we have taken a dictionary having some keys and values. After that, we have passed one key-value pair into the update function. The update function will update the key-value pair in the original dictionary. Here when the dictionary is updated, keys are automatically updated.

Example 3: Iterating using Key and Value

Code:

Output:

Example 4: Demonstrating the Practical Application of keys()

Code:

Output:

2nd-approach is raising an error because dict_keys in Python 3 do not support indexing.

Conclusion:

  • keys() method in Python is used to retrieve all of the keys from the dictionary.
  • The keys must be of an immutable type (string, number, or tuple with immutable elements) and must be unique.
  • Each key is separated from its value by a colon(:).
  • An item has a key and a value is stated as a pair (key : pair).

See also: