Dictionaries: Look Things Up by Name

What is a dictionary?

A dictionary (dict) stores pairs: a key and its value. You look values up by their key instead of by a number.

Think of it like this: A real dictionary: you look up a word (the key) to find its meaning (the value). A phone's contacts work the same way: name → phone number.

student = {
    "name": "Asha",
    "age": 21,
    "city": "Pune",
}
print(student["name"])
print(student["age"])

Output

Asha
21

Keys and values are joined with a colon :, and pairs are separated by commas.

Adding and changing

Assigning to a key adds it if it's new, or changes it if it already exists:

student = {"name": "Asha", "age": 21}
student["age"] = 22
student["course"] = "Python"
print(student)

Output

{'name': 'Asha', 'age': 22, 'course': 'Python'}

Removing

student = {"name": "Asha", "age": 22, "course": "Python"}
del student["age"]
print(student)

Output

{'name': 'Asha', 'course': 'Python'}

Missing keys

Asking for a key that isn't there causes a KeyError:

student = {"name": "Asha"}
print(student["phone"])

Output (Python stops with an error)

KeyError: 'phone'

get() is safer: it gives None (or a default you choose) instead of crashing:

student = {"name": "Asha"}
print(student.get("phone"))
print(student.get("phone", "not saved"))
print("name" in student)

Output

None
not saved
True

Remember: Keys must be unique. If you use the same key twice, the second value replaces the first.

HOME LEARN COMMUNITY DASHBOARD