The Python keys method on dictionary returns an object that contains all the keys of the dictionary under examination.
This method has no parameters, so the syntax is simply as follows:
d.key()
Let’s take some practical examples of use to better understand how this method works.
Python keys Dictionary – first example
Given any dictionary, return all of its keys.
student = {
'name': 'Cristina', 'age': 20, 'mail': 'info@codingcreativo.it'
}
print(student.keys())
The output generated will therefore be this: dict_keys ([‘name’, ‘age’, ‘mail’])
Python keys Dictionary – second example
Now suppose we have a dictionary composed of values which are in turn dictionaries. To be able to access the keys we must first select the key whose value we want to obtain.
Here is therefore a possible solution to the proposed algorithm:
students = {
'1': {'name' : 'Cristina', 'age': 29, 'mail': 'info@codingcreativo.it'},
'2': {'name' : 'Tom', 'age': 23, 'mail': 'info@prova.it'}
}
student = students.get('1', {}).keys()
print(student)
Python keys Dictionary – third example
In this third example we cycle to have all the keys. In this case the keys are the same for each element, but it might not be the case.
Here is an example with the same keys first:
'''
Example with the same keys
'''
students = {
'1': {'name' : 'Cristina', 'age': 29, 'mail': 'info@codingcreativo.it'},
'2': {'name' : 'Tom', 'age': 23, 'mail': 'info@prova.it'}
}
for student in students.values():
print(student.keys())
In output we will have the same result twice.
Now let’s take an example where the keys are different, always using Python keys() method on dictionary.
'''
Example with different keys
'''
students = {
'1': {'name' : 'Cristina', 'age': 29, 'mail': 'info@codingcreativo.it'},
'2': {'exam' : 'English', 'vote': 30}
}
for student in students.values():
print(student.keys())
In this case the results will obviously be different.
Always try the code in the following link to the Python online compiler, to test it and try alternatives to the proposed solutions. The link will open on a new page for the convenience of testing the code. Have a good time!
Conclusion
In this lesson we have introduced the keys method on dictionaries in Python and we have proposed some very simple examples to better understand how it works.
Some useful links
How to find the maximum of N numbers