Table of Contents
Dictionaries in Python are very useful because they allow you to add, read, and remove key-value pairs.
When working with them, you will oftentimes need to know if a dictionary contains a key or not.
In this post, we'll learn how to check if a key exists in a dictionary in Python.
How to check if a key exists in a dictionary in Python
To start, let's create a dictionary:
PYTHONdictionary = {
    "name": "John",
    "age": 30,
    "city": "New York"
}
print(dictionary)
The output will be:
PYTHON{'name': 'John', 'age': 30, 'city': 'New York'}
Now, let's say we want to check if the key "name" exists in the dictionary.
The best way to do this is to simply use the in keyword.
This keyword will return True if the key exists in the dictionary, and False if it doesn't.
PYTHONdictionary = {
    "name": "John",
    "age": 30,
    "city": "New York"
}
key = "name"
if key in dictionary:
    print("Key exists in dictionary")
else:
    print("Key does not exist in dictionary")
BASHKey exists in dictionary
Alternatively, you can also set the output of the in keyword to a variable:
PYTHONdictionary = {
    "name": "John",
    "age": 30,
    "city": "New York"
}
key = "name"
key_exists = key in dictionary
print(key_exists)
BASHTrue
Conclusion
In this post, we learned how to check if a key exists in a dictionary in Python.
Simply use the in keyword on a dictionary and pass it the key you want to check.
Thanks for reading!
 Getting Started with TypeScript Getting Started with TypeScript
 Getting Started with Express Getting Started with Express
 Best Visual Studio Code Extensions for 2022 Best Visual Studio Code Extensions for 2022
 How to build a Discord bot using TypeScript How to build a Discord bot using TypeScript
 Getting Started with Deno Getting Started with Deno
 How to deploy an Express app using Docker How to deploy an Express app using Docker
 How to deploy a Node app using Docker How to deploy a Node app using Docker
 How to Scrape the Web using Node.js and Puppeteer How to Scrape the Web using Node.js and Puppeteer
 Getting User Location using JavaScript's Geolocation API Getting User Location using JavaScript's Geolocation API
 Creating a Twitter bot with Node.js Creating a Twitter bot with Node.js
 Getting Started with React Getting Started with React
 Getting Started with Vuex: Managing State in Vue Getting Started with Vuex: Managing State in Vue
