How to Check if an Element Exists in a Dictionary in Python



Python


In this article, we show how to check if an element exists in a dictionary in Python.

For example, let's say we have a dictionary of stocks.

We want to check if this dictionary has the stock google, which has the symbol GOOG. If it does contain the stock GOOG, we want to return its stock price. If it doesn't, we want to return, "The price of this stock is unavailable".

In essence, we are checking to see if this item (GOOG) is in the dictionary.

There are a few ways of doing this in Python.

One way of doing this using the in keyword in Python.

This is shown below.



So, in the code above, we have a dictionary called stocks that contains the stock prices of amazon (AMZN), apple (AAPL), google (GOOG), and verizon (VZ).

Once we've created this dictonary, we then check to see if google's stock is in it.

We do this with an if statement using the in keyword. The in keyword returns true only if "GOOG" is in the stocks dictionary. In this case, the price of google's stock is printed out. If not, the else statement is executed. In this case, the statement, "The price of this stock is unavailable" is printed out.

Another way of doing this is through the get() function.

This is shown below.



The code above can be seen as a shorthand way of writing the same code as the first example.

We have the same exact dictionary named stocks.

We then create a variable named value. We set it equal to stocks.get() function with the first parameter inside the function being the ticker symbol of the stock price that you want to retrieve and the second parameter being the value that you want returned if the stock symbol is not in the stocks dictionary.

So, these are the ways you can check to see if an element exists in a dictionary in Python.


Related Resources

How to Show All Tables of a MySQL Database in Python

How to Count the Number of Rows in a MySQL Table in Python



HTML Comment Box is loading comments...