This Python Dictionaries lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.
A dictionary maps keys to values. Lookups use the key, not a position. get returns a default when the key is missing instead of raising an error.
Keys are usually strings or numbers. Values can be any object, including a list.
Example 1: Start here
A missing key with square brackets raises KeyError. get is the safer read.
learner = {"name": "Meera", "city": "Chennai", "score": 82} # a dictionary; each key has one value
print(learner["name"])
print(learner.get("phone", "not set")) # the fallback is used when the key is missing
Example 2: Read a key
Square brackets look up a key. The key must exist.
learner = {"name": "Asha", "city": "Chennai"} # a dictionary; each key has one value
print(learner["name"])
Example 3: A safe lookup
get returns the fallback when the key is absent, instead of raising an error.
learner = {"name": "Asha"} # a dictionary; each key has one value
print(learner.get("score", "missing")) # the fallback is used when the key is missing
Example 4: Add a key
Assigning a new key adds it to the dictionary.
learner = {"name": "Asha"} # a dictionary; each key has one value
learner["score"] = 82 # change this one field
print(learner)
