Python keys() Function

The keys() function in Python returns the list of all keys of a specified dictionary as a view object. For example:

x = {"Name": "Sophia", "Course": "EECS", "Age": "20"}

The output will be the list of keys, that is:

dict_keys(['Name', 'Course', 'Age'])

Note - View objects provides the dynamic view on the entries of dictionary. Therefore, when the dictionary changes, the view definitely reflects the change.

Python keys() Function Syntax

The syntax of keys() function in Python, is:


Python keys() Function Example

Here is an example demonstrating the keys() function in Python. This program allows user to add new item to the dictionary at run-time of the program:

x = {"Name": "Sophia", "Course": "EECS", "Age": "20"}

print("\n----Enter the new item to add in dictionary----")
print("Enter the key: ", end="")
key = input()
print("Enter the value: ", end="")
val = input()

x[key] = val

print("\nNew view object of all keys:")

The snapshot given below shows the sample run of above program, with user input City as new key and Liverpool as its value:

python keys function

Python Online Test

« Previous Function Next Function »

Like/Share Us on Facebook 😋