Editor settings

General settings

Save settings

Learn to program with Python

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 city should be "New York"
  • Use [] to access the value
Output will be displayed here