Check if Key Exists in Dictionary

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In Python, a dictionary is a collection of key-value pairs. Each key is unique and is used to access its corresponding value. In this challenge, you will write a function that checks if a given key exists in a dictionary.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") subgraph Lab Skills python/comments -.-> lab-13676{{"`Check if Key Exists in Dictionary`"}} python/booleans -.-> lab-13676{{"`Check if Key Exists in Dictionary`"}} python/tuples -.-> lab-13676{{"`Check if Key Exists in Dictionary`"}} python/dictionaries -.-> lab-13676{{"`Check if Key Exists in Dictionary`"}} python/function_definition -.-> lab-13676{{"`Check if Key Exists in Dictionary`"}} end

Check if Key Exists in Dictionary

Write a function key_in_dict(d, key) that takes a dictionary d and a key key as arguments and returns True if the key exists in the dictionary, False otherwise.

def key_in_dict(d, key):
  return (key in d)
d = {'one': 1, 'three': 3, 'five': 5, 'two': 2, 'four': 4}
key_in_dict(d, 'three') ## True

Summary

In this challenge, you learned how to check if a key exists in a dictionary in Python. You can use the in operator to check if a dictionary contains a specific key.

Other Python Tutorials you may like