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:
Introduction to Scientific Programming with Python - Joakim Sundnes
Python String isnumeric()
Python tuple()
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python timestamp to datetime and vice-versa
Python Program to Compute all the Permutation of the String
Python issubclass()
Python String isdigit()
Python pow()
Python break and continue
Python Program to Remove Duplicate Element From a List
Python Program to Solve Quadratic Equation
Python Program to Find Armstrong Number in an Interval
Python Multiple Inheritance
Python Program to Check If a List is Empty
Python Program to Check If a String Is a Number (Float)
Python String lstrip()
Python Generators
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python Shallow Copy and Deep Copy
Python Program to Display Calendar
Python hash()
Python List count()
Python print()
Python Program to Find HCF or GCD
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python Function Arguments
Python filter()
Python Program to Measure the Elapsed Time in Python
Python Dictionary clear()
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty