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 timestamp to datetime and vice-versa
Python List count()
Python Matrices and NumPy Arrays
Python Data Types
APIs in Node.js vs Python - A Comparison
Python exec()
Python Program to Find the Sum of Natural Numbers
Python Dictionary clear()
Python Program to Merge Mails
Python list()
Python Program to Concatenate Two Lists
Python Program to Count the Occurrence of an Item in a List
Python Program to Randomly Select an Element From the List
Python zip()
Python Set add()
Python Program to Convert Bytes to a String
Python Program to Check Whether a String is Palindrome or Not
Python Set union()
Python Directory and Files Management
Python id()
Python help()
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python Program to Find Hash of File
Python Keywords and Identifiers
Python Program to Parse a String to a Float or Int
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python Program to Find Factorial of Number Using Recursion
Python Program to Split a List Into Evenly Sized Chunks
Python Get Current time
Python Program to Convert Decimal to Binary Using Recursion
Python Set isdisjoint()
Python if...else Statement