Accessing a value in a dictionary #
You can access a value in a dictionary by using sqare brackets [] and its key, like this dict[key]:
For example:
my_dict = {
"name": "John", # <--- my_dict["name"]
"age": 25, # <--- my_dict["age"]
"city": "New York",
}
name = my_dict["name"]
print(name) # "John"
In the example above, we retrieve the value of the key "city" of the dictionary my_dict and assign it to the variable name.
Exercise #
Create a new variable city and assign its value to be"New York" by accessing it from the given dictionary.
Tests #
- Variable
cityshould be"New York" - Use
[]to access the value
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules