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 getattr()
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Python sleep()
Python Program to Illustrate Different Set Operations
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Python Set discard()
Python Program to Safely Create a Nested Directory
Python Program to Create Pyramid Patterns
Python Program to Copy a File
Python Program to Find the Size (Resolution) of a Image
Python compile()
Python Operators
Python input()
Python Shallow Copy and Deep Copy
Python list()
Python bytearray()
Python __import__()
Python Multiple Inheritance
Python Directory and Files Management
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python Program to Differentiate Between del, remove, and pop on a List
Python Set add()
Python Program to Convert Kilometers to Miles
Python String istitle()
Python int()
Python Program to Merge Mails
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python Set issuperset()
Python Generators
Python vars()
Python String rjust()
Python Program to Find Hash of File