C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Python Dictionary keys() MethodPython keys() method is used to fetch all the keys from the dictionary. It returns a list of keys and an empty list if the dictionary is empty. This method does not take any parameter. Syntax of the method is given below. Signature
keys() Parameters
No parameter ReturnIt returns a list of keys. None if the dictionary is empty. Let's see some examples of keys() method to understand it's functionality. Python Dictionary keys() Method Example 1
Let's first see a simple example to fetch keys from the dictionary.
# Python dictionary keys() Method
# Creating a dictionary
product = {'name':'laptop','brand':'hp','price':80000}
# Calling method
p = product.keys()
print(p)
Output: dict_keys(['name', 'brand', 'price']) Python Dictionary keys() Method Example 2
# Python dictionary keys() Method
# Creating a dictionary
product = {'name':'laptop','brand':'hp','price':80000}
# Iterating using key and value
for p in product.keys():
if p == 'price' and product[p] > 50000:
print("product price is too high",)
Output: product price is too high Python Dictionary keys() Method Example 3We can use this method into our python program. Here, we are using it into a program to check our inventory status.
# Python dictionary keys() Method
# Creating a dictionary
inventory = {'apples': 25, 'bananas': 220, 'oranges': 525, 'pears': 217}
# Calling method
for akey in inventory.keys():
if akey == 'bananas' and inventory[akey] > 200:
print("We have sufficient inventory for the ", akey)
Output: We have sufficient inventory for the bananas
Next TopicPython Dictionary
|