Lists and tuples store values in order, and you access each one by its position: index 0, index 1, and so on. But sometimes position isn’t a natural way to think about your data. If you’re storing a person’s details- name, age, city- you don’t want to remember that age is “item number 1.” You want to just ask for age directly. That’s what a dictionary is built for.
What a dictionary actually is
A dictionary stores data as key-value pairs. Each key acts like a label, and it points to a value. You create one with curly braces.
student = {"name": "Sujan", "age": 16, "city": "Kathmandu"}
print(student)
"""Output:
{'name': 'Sujan', 'age': 16, 'city': 'Kathmandu'}"""Accessing values by key
No index numbers here: you access a value using its key instead.
student = {"name": "Sujan", "age": 16, "city": "Kathmandu"}
print(student["name"]) # Sujan
print(student["age"]) # 16Try to access a key that doesn’t exist, and Python throws an error.
print(student["grade"])
"""Output
KeyError: 'grade' """A safer way to access a value is with.get(), which returns None instead of crashing if the key isn’t there.
print(student.get("grade")) # None
print(student.get("grade", "N/A")) # N/AAdding or updating a value
student = {"name": "Sujan", "age": 16}
student["city"] = "Kathmandu" # adds a new key
student["age"] = 17 # updates an existing key
print(student)
"""{'name': 'Sujan', 'age': 17, 'city': 'Kathmandu'}"""If the key already exists, Python updates it. If it doesn’t, Python adds it as new. Same syntax either way.
Removing a key
student = {"name": "Sujan", "age": 16, "city": "Kathmandu"}
del student["city"]
print(student) # {'name': 'Sujan', 'age': 16}You can also use .pop(), which removes the key and returns its value, similar to how pop() worked on a list.
age = student.pop("age")
print(age) # 16
print(student) # {'name': 'Sujan'}Looping through a dictionary
student = {"name": "Sujan", "age": 16, "city": "Kathmandu"}
for key in student:
print(key, ":", student[key])
""" Output
name : Sujan
age : 16
city : Kathmandu"""A cleaner way to do the same thing uses .items(), which gives you both the key and value directly.
for key, value in student.items():
print(key, ":", value)Checking if a key exists
student = {"name": "Sujan", "age": 16}
print("name" in student) # True
print("grade" in student) # FalseSame in operator you’ve already used on strings, lists, and tuples; it checks keys here, not values.
keys(), values(), and len()
student = {"name": "Sujan", "age": 16, "city": "Kathmandu"}
print(student.keys()) # dict_keys(['name', 'age', 'city'])
print(student.values()) # dict_values(['Sujan', 16, 'Kathmandu'])
print(len(student)) # 3Python Dictionary Practice Questions
- Create a dictionary representing a book with keys for title, author, and year. Print the author.
- What is the output of the following code?
info = {"a": 1, "b": 2} print(info.get("c", "not found")) - Write code that adds a new key “grade” with value “A” to an existing dictionary.
- Write a loop that prints every key and value in a dictionary using
.items(). - What error occurs if you try to access a key that doesn’t exist using square brackets? How would you avoid it?
- Write a program that removes a key called “age” from a dictionary and prints its value before removing it.
