Table of Contents
The keys() method returns a view object that displays a list of all the keys in the dictionary
The syntax of keys() is:
dict.keys()
1. keys() Parameters
keys() doesn’t take any parameters.
2. Return Value from keys()
keys() returns a view object that displays a list of all the keys.
When the dictionary is changed, the view object also reflects these changes.
3. Example 1: How keys() works?
person = {'name': 'Phill', 'age': 22, 'salary': 3500.0}
print(person.keys())
empty_dict = {}
print(empty_dict.keys())
Output
dict_keys(['name', 'salary', 'age']) dict_keys([])
4. Example 2: How keys() works when dictionary is updated?
person = {'name': 'Phill', 'age': 22, }
print('Before dictionary is updated')
keys = person.keys()
print(keys)
# adding an element to the dictionary
person.update({'salary': 3500.0})
print('\nAfter dictionary is updated')
print(keys)
Output
Before dictionary is updated dict_keys(['name', 'age']) After dictionary is updated dict_keys(['name', 'age', 'salary'])
Here, when the dictionary is updated, keys is also automatically updated to reflect changes.
Related posts:
Python Set union()
Python Package
Python any()
Python Shallow Copy and Deep Copy
Python Program to Delete an Element From a Dictionary
Python Program to Get the Full Path of the Current Working Directory
Python Program to Count the Number of Each Vowel
Python String center()
Python String rfind()
Python Program to Convert String to Datetime
Python Program to Convert Two Lists Into a Dictionary
Python input()
Python Program to Find LCM
Python Data Types
Python if...else Statement
Python Program to Create Pyramid Patterns
Python hash()
Python Program to Access Index of a List Using for Loop
Python Dictionary pop()
Python Program to Check If a List is Empty
Python Set discard()
Python List pop()
Python Machine Learning - Sebastian Raschka
Python float()
Python Keywords and Identifiers
Deep Learning with Python - Francois Cholletf
Python Program to Check If a String Is a Number (Float)
Python Program to Print Hello world!
Python Global, Local and Nonlocal variables
Python Program to Find the Factors of a Number
Python Program to Compute the Power of a Number
Python Program to Find the Sum of Natural Numbers