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 Append to a File
Python format()
Python Set symmetric_difference()
Python Set union()
Python Program to Remove Duplicate Element From a List
Python String isalnum()
Python Program to Find All File with .txt Extension Present Inside a Directory
Python next()
Python sorted()
Python String endswith()
Python List remove()
Python slice()
Python Deep Learning Cookbook - Indra den Bakker
Python len()
Python Set intersection()
Python Program to Create a Long Multiline String
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python Program to Count the Occurrence of an Item in a List
Python Program to Reverse a Number
Python open()
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Introduction to Scientific Programming with Python - Joakim Sundnes
Python Dictionary popitem()
Python Variables, Constants and Literals
Python help()
Python Multiple Inheritance
Python Program to Catch Multiple Exceptions in One Line
Python Generators
Python Program to Find the Largest Among Three Numbers
Python Program to Safely Create a Nested Directory
Python Program to Display Powers of 2 Using Anonymous Function
Python hash()