
Syntax: Dict Get and In Keyword
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
-
Create a dictionary
studentwith keys"name","id", and"course"and assign appropriate values to each key. -
Print the value for the key
"id"using thegetmethod. -
Check if the key
"age"exists in the dictionary using theinkeyword and print the result.
HINT*: Click here for a hint
> 123
> False
SOLUTION*: Click here for an example solution
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.