What is a Dictionary?
A dictionary stores data as pairs of keys and values. Instead of using a number position like a list, you look items up by a meaningful key. Dictionaries use curly braces, with each key and value separated by a colon.
student = {'name': 'Amina', 'age': 20}
print(student['name']) # Amina
print(student['age']) # 20
Keys are usually strings or numbers and must be unique. Values can be anything and may repeat.
Adding and Changing Items
You can add a new pair or update an existing one just by assigning to a key.
student = {'name': 'Amina'}
student['age'] = 20 # adds a new pair
student['name'] = 'Ben' # updates the value
print(student) # {'name': 'Ben', 'age': 20}
Reading Values Safely
Using square brackets on a key that does not exist raises a KeyError. To avoid crashes, use the get() method, which returns None (or a default you choose) when the key is missing.
student = {'name': 'Amina'}
print(student.get('age')) # None
print(student.get('age', 0)) # 0
Looping Through a Dictionary
Looping over a dictionary gives you its keys by default. The methods keys(), values(), and items() let you loop over each part.
scores = {'maths': 90, 'science': 85}
for subject in scores:
print(subject, scores[subject])
for key, value in scores.items():
print(key, value)
The len() function tells you how many pairs a dictionary holds.
print(len({'a': 1, 'b': 2})) # 2
Removing Items and Checking Membership
You can delete a pair with the del keyword or the pop() method, and you can test whether a key exists with the in operator. Checking membership this way is fast and reads naturally.
student = {'name': 'Amina', 'age': 20}
print('name' in student) # True
del student['age']
print(student) # {'name': 'Amina'}
Dictionaries are one of the most useful tools in Python because they let you organise related information under clear, meaningful labels rather than remembering number positions. They are ideal for counting things, grouping records, and storing settings, which is why you will see them in almost every real program you read.
Remember
- Dictionaries store key and value pairs inside curly braces.
- Keys must be unique; values may repeat.
- Square brackets on a missing key raise a KeyError.
- Use get() to read safely and supply a default value.
- Use items() to loop over keys and values together.