Python provides the dictionary type in order to store data in key and value pairs. The keys are used to show values like a real dictionary where a word has a meaning. In order to work with dictionaries, the keys are important where keys will redirect us to values. The dictionary type provides the keys()
method in order to work with dictionary keys.
keys() Method Syntax
The keys() method has very simple syntax where it does not require any parameter. The key() method returns the list of all keys for the dictionary.
DICT.keys()
List All Keys
The only function of the keys() method is returning the list of keys for the specified dictionary.
d = {'name':'İsmail','surname':'Baydan','age':38}
print(d.keys())
dict_keys(['name', 'surname', 'age'])
The output returns the dict_keys
type which contains the list of the dictionary keys.
Add New Key/Value
New key and values pairs can be added to the existing dictionary. This means a new key will be added too. The newly added key can be displayed with the keys()
method.
d = {'name':'İsmail','surname':'Baydan','age':38}
print(d.keys())
d.update({'location': 'Turkey'})
print(d.keys())
dict_keys(['name', 'surname', 'age']) dict_keys(['name', 'surname', 'age', 'location'])
Convert Dictionary Keys To List
By default, the keys() method returns the keys as dict_keys type. The list()
function can be used to convert these keys into a list like below.
d = {'name':'İsmail','surname':'Baydan','age':38}
l=list(d.keys())
print(l)
['name', 'surname', 'age']
Print First Key
By using the keys() method the first key of a dictionary can be printed like below.
d = {'name':'İsmail','surname':'Baydan','age':38}
l=list(d.keys())
print(l[0])
Print Last Key
Also, the last key of the dictionary can be printed like below.
d = {'name':'İsmail','surname':'Baydan','age':38}
l=list(d.keys())
print(l[-1])