Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python – How to Check if a Dict Key Exists?

#1
Python – How to Check if a Dict Key Exists?

  • Summary: To check whether a key exists in a dictionary, you can use:
    • The in keyword
    • The keys() method
    • The get() method
    • The has_key() method    

Overview


Mastering dictionaries is one of the things that differentiates the expert coders from the intermediate coders. Why? Because dictionaries in Python have many excellent properties in terms of runtime—and they’re very easy to use and understand. You cannot write effective code in Python without leveraging this powerful data structure. So, let’s dive into the mission-critical question:

Problem: Given a dictionary in Python; how to check if a specific key exists within the dictionary?

device = { "brand": "Apple", "model": "iPhone 11",
}
# <Some Method to Check if the keys "brand" and "year" exists in the dictionary or not>

While working with dictionaries, you will often come across scenarios where you have to extract a certain key-value from the dictionary. However, what if the key that you want to access is not present within the dictionary? This is what happens when you do so:


Hence, it is always a good practice to check if a key exists in the dictionary or not before extracting the value. So, without further delay, let us dive into the methods used to check the existence of a key in a dictionary:

? Method 1: Using The in Keyword


in is a keyword in Python which has two primary uses:

  • It is used to verify if a given value is present in a sequence (dictionary, string, tuple, list, etc.)
  • It can be used in a for loop to iterate through the items of a sequence.

Example:

li = [1,2,3,4,5]
# Use 1: check if "1" is present in the list
print(1 in li)
# Use 2: iterate through items in li
for i in li: print(i, end=" ")

Output:

True
1 2 3 4 5

? Thus, you can use the in keyword within the if-else statements to check if a key is already present in the given dictionary. 

Example:

device = { "brand": "Apple", "model": "iPhone 11", "year": 2018
}
if "year" in device: print("key year is present!")
else: print("key year is not Present!")
if "color" in device: print("key color is present!")
else: print("key color is not present!")

Output:

key year is present!
key color is not present!

? Method 2: Using The keys() Method


keys() is an inbuilt method in Python that extracts the keys present in a dictionary and stores them in a list. It returns a view object that contains the keys of the dictionary in a list.

Syntax: dictionary.keys()

Example:

car = { "Name": "Sam", "ID": "1094786", "DOB": "21-08-1964"
}
x = car.keys()
print(x)

Output:

dict_keys(['Name', 'ID', 'DOB'])

? Thus, with the help of the keys() method and if-else statements, you can determine if a key is present in the dictionary.

Example: 

device = { "brand": "Apple", "model": "iPhone 11", "year": 2018
}
if "year" in device.keys(): print("key -> 'year' is Present!")
else: print("key -> 'year' is Not Present!")
if "color" in device.keys(): print("key -> 'color' is Present!")
else: print("key -> 'color' is Not Present!")

Output:

key -> 'year' is Present!
key -> 'color' is Not Present!

? Method 3: Using get() Method


get() is a dictionary method in Python that returns an item’s value with a specified key.

Syntax:

dictionary.get(keyname, value)
  • If the key is present in the dictionary the get() will return the value of the key, else it will return None
  • Hence, you can use the if-else statements to check if the value returned by the key is not None; which means the key is not present in the dictionary and vice-versa.

Example:

device = { "brand": "Apple", "model": "iPhone 11", "year": 2018
}
if device.get("year") is not None: print("key->'year' is Present!")
else: print("key year is not Present!")
if device.get("color") is not None: print("key->'color' is Present!")
else: print("key->'color' is Not Present!")

Output:

key->'year' is Present!
key->'color' is Not Present!

? Method 4: Using has_key() Function


If you are using Python 2.x then you might fancy your chances with the has_key() method which is an inbuilt method in Python that returns true if the specified key is present in the dictionary. Otherwise, it returns false.

⚠ Caution: has_key() has been removed from Python 3 and also lags behind the in keyword while checking for the presence of keys in a dictionary in terms of performance. So you must avoid using it if you are using Python 3 or above.

Now let us have a look at the following program to understand how we can use the has_key() method:

device = { "brand": "Apple", "model": "iPhone 11", "year": 2018
}
if device.has_key("year"): print("key->'year' is present!")
else: print("key->'year' is not Present!")
if device.has_key("color"): print("key->'color' is present!")
else: print("key->'color' is not present!")

Output:

key->'year' is present!
key->'color' is not present!

Conclusion


In this tutorial, you learned about numerous methods that can be used to check if a specific key exists in a dictionary. I hope it helped you and answered all your queries. Please subscribe and stay tuned for more interesting articles.

Here’s a list of related articles that are highly recommended if you want to master dictionaries in Python:

The Complete Guide to PyCharm

  • Do you want to master the most popular Python IDE fast?
  • This course will take you from beginner to expert in PyCharm in ~90 minutes.
  • For any software developer, it is crucial to master the IDE well, to write, test and debug high-quality code with little effort.

Join the PyCharm Masterclass now, and master PyCharm by tomorrow!

The post Python – How to Check if a Dict Key Exists? first appeared on Finxter.



https://www.sickgaming.net/blog/2021/04/...ey-exists/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] How to Check if a Python String Contains Only Digits? xSicKxBot 0 8 04-12-2021, 12:23 PM
Last Post: xSicKxBot
  [Tut] Check If All Elements In A List Are Identical xSicKxBot 0 22 03-20-2021, 10:12 AM
Last Post: xSicKxBot
  [Tut] How to Check if an Object is of Type List in Python? xSicKxBot 0 53 02-09-2021, 08:05 AM
Last Post: xSicKxBot
  [Tut] What’s the Standard Way to Check for Type in Python? xSicKxBot 0 52 01-25-2021, 04:47 PM
Last Post: xSicKxBot
  [Tut] How to Check Whether a File Exists Without Exceptions? xSicKxBot 0 54 01-23-2021, 05:56 AM
Last Post: xSicKxBot
  [Tut] Python help() xSicKxBot 0 65 01-22-2021, 01:02 AM
Last Post: xSicKxBot
  [Tut] Python complex() — A Useless Python Feature? xSicKxBot 0 73 12-19-2020, 02:05 AM
Last Post: xSicKxBot
  [Tut] Python next() xSicKxBot 0 69 11-22-2020, 08:17 AM
Last Post: xSicKxBot
  [Tut] Hello World! A Python One-Liner to Get Started with Python Quickly xSicKxBot 0 121 09-07-2020, 06:10 PM
Last Post: xSicKxBot
  [Tut] Dict to List — How to Convert a Dictionary to a List in Python xSicKxBot 0 142 06-30-2020, 04:53 AM
Last Post: xSicKxBot

Forum Jump:

[-]
Active Threads
(Indie Deal) FREE Stranded In Time | XCO...
Last Post: xSicKxBot
Today 07:54 AM
» Replies: 0
» Views: 0
Microsoft - 5 reasons to attend Azure St...
Last Post: xSicKxBot
Today 07:54 AM
» Replies: 0
» Views: 0
News - Deals: Ring Fit Adventure Is Down...
Last Post: xSicKxBot
Today 07:54 AM
» Replies: 0
» Views: 0
News - Cuphead Will Have An Awesome Deca...
Last Post: xSicKxBot
Today 07:54 AM
» Replies: 0
» Views: 0
News - Nintendo Actually Responded To A ...
Last Post: xSicKxBot
Today 01:50 AM
» Replies: 0
» Views: 6
News - Rumour: Dragon Ball Z: Kakarot Co...
Last Post: xSicKxBot
Today 01:50 AM
» Replies: 0
» Views: 6
Xbox Wire - Next Week on Xbox: April 6 t...
Last Post: xSicKxBot
Yesterday 11:48 PM
» Replies: 0
» Views: 7
News - Ubisoft hires ex-Uber HR director...
Last Post: xSicKxBot
Yesterday 11:48 PM
» Replies: 0
» Views: 13
News - Blog: An essential guide to live ...
Last Post: xSicKxBot
Yesterday 11:48 PM
» Replies: 0
» Views: 14
[Tut] Python Dash Book
Last Post: xSicKxBot
Yesterday 05:52 PM
» Replies: 0
» Views: 6

[-]
Twitter

[-]
Sponsored
Get the Deal of the Week at RefurBees.com

Copyright © SickGaming.net 2012-2020