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.
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:
for key in dictionary_name:
print(key)
Program:
# Python program to get the keys of a dictionary
# by looping through a dictionary
# creating the dictionary
dict_a = {'id' : 101, 'name' : 'Amit', 'age': 21}
# printing the dictionaries
print("Dictionary \'dict_a\' is...")
print(dict_a)
# looping through a dictionary
# and, printing the keys
print("Keys of the Dictionary \'dict_a\'...")
for x in dict_a:
print(x)
Output:
Dictionary 'dict_a' is...
{'name': 'Amit', 'id': 101, 'age': 21}
Keys of the Dictionary 'dict_a'...
name
id
age
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:
dictionary_name.keys()
Program:
# Python program to get the keys of a dictionary
# by using the keys() method
# creating the dictionary
dict_a = {'id' : 101, 'name' : 'Amit', 'age': 21}
# printing the dictionaries
print("Dictionary \'dict_a\' is...")
print(dict_a)
# getting the keys of a dictionary
# using keys() method and, printing the keys
print("Keys of the Dictionary \'dict_a\'...")
print(dict_a.keys())
Output:
Dictionary 'dict_a' is...
{'name': 'Amit', 'id': 101, 'age': 21}
Keys of the Dictionary 'dict_a'...
dict_keys(['name', 'id', 'age'])
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