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 String isdecimal()
Python Dictionary clear()
Python Program to Iterate Through Two Lists in Parallel
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python for Loop
Python Program to Generate a Random Number
Python String partition()
Python oct()
Python getattr()
Python Set difference_update()
Python List insert()
Python Program to Find Hash of File
Python Program to Create Pyramid Patterns
Python repr()
Python ord()
Python Program to Parse a String to a Float or Int
Python if...else Statement
Introduction to Scientific Programming with Python - Joakim Sundnes
Python Program to Compute the Power of a Number
Python String splitlines()
Python set()
Python String rjust()
Python List Comprehension
Python Program to Find ASCII Value of Character
Python exec()
Python Namespace and Scope
Python datetime
Python globals()
Python Program to Print Hello world!
Python Program to Reverse a Number
Python setattr()
Python ascii()