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 Program to Copy a File
Python pow()
Python getattr()
Python Program to Check If a String Is a Number (Float)
Python sorted()
Python Program to Print the Fibonacci sequence
Python List Comprehension
Python Dictionary pop()
Python Multiple Inheritance
Python String expandtabs()
How to get current date and time in Python?
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python Errors and Built-in Exceptions
Python String swapcase()
Python isinstance()
Python Program to Safely Create a Nested Directory
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Python Set pop()
Python String replace()
Python Program to Merge Mails
Python divmod()
Python Program to Create Pyramid Patterns
Python String rindex()
Python Machine Learning Eqution Reference - Sebastian Raschka
Deep Learning in Python - LazyProgrammer
Python print()
Python sleep()
Python String format()
Python Set difference()
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python List clear()
Python List count()