Checking for Keys
Part of the Logic & Flow section of Coddy's Python journey — lesson 14 of 78.
When working with dictionaries, you often need to check if a specific key exists. Python provides simple ways to check for the presence of keys in a dictionary.
Using the in keyword:
my_dict = {'name': 'Alice', 'age': 30}
# Check if 'name' is a key in the dictionary
if 'name' in my_dict:
print('Name exists in the dictionary')
# Check if 'city' is a key in the dictionary
if 'city' not in my_dict:
print('City does not exist in the dictionary')In this example, we use the in keyword to check if 'name' is one of the keys in my_dict. We also use not in to check if 'city' is not a key in the dictionary.
Using the keys() method:
my_dict = {'name': 'Alice', 'age': 30}
# Check if 'age' is in the keys
if 'age' in my_dict.keys():
print('Age exists in the dictionary')Here, my_dict.keys() returns a view object containing all keys in the dictionary, and we use in to check if 'age' is in that list.
Challenge
EasyYou are managing a dictionary of employee data, where each key is an employee's name and the value is their department. Your task is to:
- Check if
"Alice"is a key in the dictionary.- If it exists, print:
"Alice is in the company."
- If it exists, print:
- Check if
"John"is not a key in the dictionary.- If it does not exist, print:
"John is not in the company."
- If it does not exist, print:
Cheat sheet
To check if a key exists in a dictionary, use the in keyword:
my_dict = {'name': 'Alice', 'age': 30}
# Check if key exists
if 'name' in my_dict:
print('Name exists in the dictionary')
# Check if key does not exist
if 'city' not in my_dict:
print('City does not exist in the dictionary')You can also use the keys() method:
# Check if key is in the list of keys
if 'age' in my_dict.keys():
print('Age exists in the dictionary')Try it yourself
employees = {"Alice": "HR", "Bob": "Engineering", "Diana": "Marketing"}
# Write code hereThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Variables Exploration
ConstantsMultiple Variable AssignmentsSwapping VariablesPlaceholder VariablesRound NumbersList Casting4Contact Book Application
Display MenuAdd Contact7Sets Part 2
Mathematical Operations Part 1Mathematical Operations Part 2Recap - Treasure HuntSubsets and SupersetsIterating Over SetsRecap - Tournament Tracker2Dictionaries Part 1
What is a Dictionary?Creating a DictionaryAccessing ValuesModifying DictionariesRecap - Recipe Manager5Advanced Decision Making
Ternary OperatorMembership ChecksIdentity ChecksIndentation ErrorsRecap - Vacation Filter8Student Records Manager
Project OverviewAdd Student11Advanced Functions
Returning Multiple ValuesLambda Functions Part 1Lambda Functions Part 2Recap Challenge - Lambda SortRecursive Functions Part 1Recursive Functions Part 2Recap - Sum Nested List14Higher-Order Functions
The Map FunctionThe Filter FunctionRecap - Email ValidatorRecap - Number Processor3Dictionaries Part 2
Dictionary MethodsNested DictionariesChecking for KeysLooping Through DictionariesRecap - Frequency Counter9Advanced Data Aggregation
Using SumFinding Minimum and MaximumSorting Data EfficientlyRecap - Dictionary Sorter