Introduction to Python Resources

Begin your free Python journey now,
at your own pace

check

Syntax: Dict Get and In Keyword

check

Finding and retrieving values in Python dictionaries.


Python provides methods to efficiently search for keys in a dictionary and retrieve the corresponding values.

Retriving a Dictionary Value by its Key

The get method retrieves the value for a given key if it exists in the dictionary, and returns None otherwise.

user = {
  "name": "Bob",
  "email": "[email protected]",
  "age": 35
}
print(user.get("name"))
print(user.get("address"))

> Bob
> None

Checking if a Dictionary Contains a Key

The in keyword checks if a key exists in the dictionary and returns a boolean value.

user = {
  "name": "Bob",
  "email": "[email protected]",
  "age": 35
}
print("name" in user)
print("address" in user)

> True
> False

Practice: Reading Dictionaries using Keys

  1. Create a dictionary student with keys "name", "id", and "course" and assign appropriate values to each key.

  2. Print the value for the key "id" using the get method.

  3. Check if the key "age" exists in the dictionary using the in keyword and print the result.

HINT*: Click here for a hint
*Hints are best viewed after completing a task, or after spending some time and effort attempting it. In cases where a hint contains example output, it is important to understand why it is correct, as there may be many correct outputs.
> 123
> False
SOLUTION*: Click here for an example solution
*Example solutions are best viewed after completing a task and understanding the outcome. In most cases, there are multiple ways to complete a task, and the example solution is only one example.
student = {
  "name": "Alice",
  "id": 123,
  "course": "Data Science"
}
print(student.get("id"))
print("age" in student)

Well done! Understanding how to use get and in with dictionaries is essential for efficiently retrieving data from dictionaries.