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 Check if a Number is Positive, Negative or 0
Python Set symmetric_difference()
Python Program to Extract Extension From the File Name
Python Directory and Files Management
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python String translate()
Python String partition()
Deep Learning with Python - Francois Chollet
Python String maketrans()
Python String rindex()
Python String casefold()
Python super()
Python Program to Check Whether a String is Palindrome or Not
Python Program to Display Powers of 2 Using Anonymous Function
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python String rpartition()
Python range()
Python Program to Return Multiple Values From a Function
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python Program to Multiply Two Matrices
Python open()
Machine Learning with Python for everyone - Mark E.Fenner
Python complex()
Python Program to Copy a File
Python Program to Check Prime Number
Python repr()
Python Program to Concatenate Two Lists
Python Program to Reverse a Number
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python Program to Find Armstrong Number in an Interval
Python Program to Get the Full Path of the Current Working Directory
Python filter()