Accessing Values
Part of the Logic & Flow section of Coddy's Python journey — lesson 9 of 78.
In a dictionary, each key is associated with a value. To access a value, you use its key. This is similar to how you would look up a word in a physical dictionary to find its definition.
Here's how you can access values in a Python dictionary:
# Dictionary of country capitals
country_capitals = {
"USA": "Washington, D.C.",
"France": "Paris",
"Japan": "Tokyo"
}
# Accessing values using keys
print(country_capitals["USA"])
print(country_capitals["France"])
# Accessing a value that does not exist
# print(country_capitals["Germany"]) # This will cause an errorIn this example, we access the capital of the USA by using the key "USA". If you try to access a key that does not exist in the dictionary, Python will raise a KeyError.
Challenge
EasyCreate a function named get_capital that takes two parameters: country_capitals (a dictionary) and country_name (a string). The function should return the capital city of the given country name using the country_capitals dictionary.
Cheat sheet
To access values in a dictionary, use the key inside square brackets:
country_capitals = {
"USA": "Washington, D.C.",
"France": "Paris",
"Japan": "Tokyo"
}
# Accessing values using keys
print(country_capitals["USA"]) # Output: Washington, D.C.
print(country_capitals["France"]) # Output: ParisAccessing a key that doesn't exist will raise a KeyError.
Try it yourself
def get_capital(country_capitals, country_name):
# Write code hereThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Variables Exploration
ConstantsMultiple Variable AssignmentsSwapping VariablesPlaceholder VariablesRound NumbersList Casting4Contact Book Application
Display MenuAdd Contact7Sets Part 2
Mathematical Operations Part 1Mathematical Operations Part 2Recap - Treasure HuntSubsets and SupersetsIterating Over SetsRecap - Tournament Tracker2Dictionaries Part 1
What is a Dictionary?Creating a DictionaryAccessing ValuesModifying DictionariesRecap - Recipe Manager5Advanced Decision Making
Ternary OperatorMembership ChecksIdentity ChecksIndentation ErrorsRecap - Vacation Filter8Student Records Manager
Project OverviewAdd Student11Advanced Functions
Returning Multiple ValuesLambda Functions Part 1Lambda Functions Part 2Recap Challenge - Lambda SortRecursive Functions Part 1Recursive Functions Part 2Recap - Sum Nested List14Higher-Order Functions
The Map FunctionThe Filter FunctionRecap - Email ValidatorRecap - Number Processor3Dictionaries Part 2
Dictionary MethodsNested DictionariesChecking for KeysLooping Through DictionariesRecap - Frequency Counter9Advanced Data Aggregation
Using SumFinding Minimum and MaximumSorting Data EfficientlyRecap - Dictionary Sorter