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 Set clear()
Python super()
Python Program to Find Sum of Natural Numbers Using Recursion
Python Program to Create Pyramid Patterns
Python print()
Python any()
Python Program to Create a Long Multiline String
Python Variables, Constants and Literals
Python Tuple
Python Program to Check if a Key is Already Present in a Dictionary
Python Program to Check If Two Strings are Anagram
Python dir()
Python String casefold()
Python String istitle()
Python Program to Convert Celsius To Fahrenheit
Python Program to Differentiate Between type() and isinstance()
Python Program to Find Armstrong Number in an Interval
Python Sets
Python sorted()
Python Program to Merge Two Dictionaries
Python Program Read a File Line by Line Into a List
Python Machine Learning Cookbook - Practical solutions from preprocessing to Deep Learning - Chris A...
Python del Statement
Python String rpartition()
Python Inheritance
Python Shallow Copy and Deep Copy
Python pass statement
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Python iter()
Python String startswith()
Python Directory and Files Management
Python Strings