A dictionary contains the pair of the keys & values (represents key : value), a dictionary is created by providing the elements within the curly braces ({}), separated by the commas.
Here, we are going to access and print the all keys of a dictionary, there are some of the ways to get the keys of a dictionary.
- Using loop through a dictionary
- Using the keys() method
1) Get the keys of a dictionary by looping through a dictionary
When we loop through a dictionary, it returns the keys only. In this way, we can get and print the all keys of a dictionary.
Syntax:
Program:
Output:
2) Get the keys of a dictionary by using the keys() method
The keys() method is a built-in method in Python and it returns a view object containing the keys of the dictionary as a list.
Syntax:
Program:
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer