Python Dictionary keys() method
Python Dictionary keys() method
The dictionary.keys() method in Python returns a view object that displays a list of all the keys in the dictionary
Syntax
dictionary.keys()
Parameter
NA
Return
This method returns a view object that displays a list of all the keys in the dictionary
Example 1
# the python program representing
# the dictionary.keys() method
# initializing the dictionary
fruits = {
"banana": "apple",
"orange": "mango",
"grapes": 5
}
# printing the Dictionary
print("Dictionary:",fruits)
# returning a view object that displays a list of all the keys in the dictionary
keysItem= fruits.keys()
# printing the keys
print("The items in the dictionary are:",keysItem)
Output
Dictionary: {'grapes': 5, 'orange': 'mango', 'banana': 'apple'}
The items in the dictionary are: dict_keys(['grapes', 'orange', 'banana'])
Example 2
# the python program representing
# the dictionary.keys() method
# initializing the week dictionary
week = { 'Monday': 1, 'Tuesday': 2, 'wednesday': 3 ,'Thursday':4,'Friday':5}
items = week.keys()
print('Original week list:', items)
# deleting an item from the week dictionary
del[week['Thursday']]
# returning a view object that displays a list of all the keys in the dictionary
print('Updated week list:', items)
Output
Original week list: dict_keys(['Tuesday', 'Friday', 'Monday', 'Thursday', 'wednesday']) Updated week list: dict_keys(['Tuesday', 'Friday', 'Monday', 'wednesday'])
Example 3
# the python program representing
# the dictionary.keys() method
# intializing Dictionary with two keys
Dictionary = {'1. ': 'Tutorials', '2. ': 'And'}
# Printing the keys of dictionary
print("Keys before Dictionary Updation:")
keys = Dictionary.keys()
print(keys)
# adding an element to the dictionary
Dictionary.update({'3.':'Examples'})
print('\nAfter updating the dictionary...')
print(keys)
Output
Keys before Dictionary Updation: dict_keys(['2. ', '1. ']) After updating the dictionary... dict_keys(['2. ', '1. ', '3.'])
