TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

Python Dictionary keys() method with Examples

Python Dictionary keys() method with Examples on clear(), copy(), fromkeys(), get(), len(), items(), keys(), setdefault(), values(), ascii(), enumerate(), update(), pop() etc.

<< Back to PYTHON

Python Dictionary keys() Method

Python 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

Return

It 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 3

We 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




Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf