person = {
"name": "John",
"age": 25,
"city": "New York",
}
print(person){'name': 'John', 'age': 25, 'city': 'New York'}
A dictionary stores data in key-value pairs. Each key identifies a value.
Dictionaries are useful for structured records, such as a person’s profile, a product catalogue, or the settings of an application.
Create a dictionary with curly brackets {}. Separate each key from its value with a colon.
person = {
"name": "John",
"age": 25,
"city": "New York",
}
print(person){'name': 'John', 'age': 25, 'city': 'New York'}
print(type(person))<class 'dict'>
Use empty curly brackets to create an empty dictionary.
empty_dictionary = {}
print(empty_dictionary){}
print(type(empty_dictionary))<class 'dict'>
Remember that an empty set uses set() instead.
empty_set = set()
print(type(empty_set))<class 'set'>
Keys must be unique and immutable. Strings, numbers, and tuples can be keys. Values can have any data type and may be duplicated.
course = {
"title": "Introduction to Python",
"students": 32,
"online": True,
"topics": ["variables", "loops", "functions"],
"room": (4, 12),
}
print(course){'title': 'Introduction to Python', 'students': 32, 'online': True, 'topics': ['variables', 'loops', 'functions'], 'room': (4, 12)}
You can also use variables when defining keys or values.
student_name = "Maya"
grade_key = "grade"
student = {
"name": student_name,
grade_key: 8.7,
"programme": "Data Science",
}
print(student){'name': 'Maya', 'grade': 8.7, 'programme': 'Data Science'}
Lists and sets cannot be dictionary keys because they are mutable. Tuples can be keys if all their items are immutable.
classrooms = {
("Monday", "09:00"): "Room A",
("Tuesday", "11:00"): "Room C",
}
print(classrooms){('Monday', '09:00'): 'Room A', ('Tuesday', '11:00'): 'Room C'}
Access a value by writing its key inside square brackets.
person = {
"name": "John",
"age": 25,
"city": "New York",
}
print(person["name"])John
print(person["age"])25
Modern Python dictionaries preserve insertion order. However, they are accessed by key, not by position.
print(person[0])KeyError: 0
The code fails because 0 is not a key in person.
Numeric keys are valid, but Python still treats them as keys rather than positions.
numbers = {
3: "three",
4: "four",
5: "five",
}
print(numbers[3])three
print(numbers[0])KeyError: 0
Square brackets raise a KeyError when the requested key does not exist.
print(person["email"])KeyError: 'email'
The get() method returns None instead of raising an error.
print(person.get("email"))None
You can provide a default value as the second argument.
print(person.get("email", "Email not available"))Email not available
Use the dictionary below to print the book’s title and publication year in separate cells.
book = {
"title": "Kindred",
"author": "Octavia Butler",
"year": 1979,
}print(book["title"])print(book["year"])Dictionaries are mutable. You can add, update, and remove key-value pairs.
Assign a new value to an existing key.
person = {
"name": "John",
"age": 25,
"city": "New York",
}
print(person){'name': 'John', 'age': 25, 'city': 'New York'}
person["age"] = 26
print(person){'name': 'John', 'age': 26, 'city': 'New York'}
Assigning a value to a new key adds a new key-value pair.
person["email"] = "john@example.com"
print(person){'name': 'John', 'age': 26, 'city': 'New York', 'email': 'john@example.com'}
Use del to remove a key and its value.
del person["city"]
print(person){'name': 'John', 'age': 26, 'email': 'john@example.com'}
The pop() method removes a key and returns its value.
removed_email = person.pop("email")
print(removed_email)john@example.com
print(person){'name': 'John', 'age': 26}
Make these changes to the dictionary:
"Main Hall"."sold_out": False."dress_code" pair.event = {
"name": "Data Night",
"venue": "Room 2",
"dress_code": "Casual",
}event["venue"] = "Main Hall"
event["sold_out"] = False
del event["dress_code"]
print(event)A dictionary cannot contain duplicate keys. If the same key appears more than once, the last value replaces the earlier value.
person = {
"name": "John",
"name": "Smith",
"age": 25,
}
print(person){'name': 'Smith', 'age': 25}
Different keys may contain the same value.
locations = {
"home_city": "Madrid",
"work_city": "Madrid",
}
print(locations){'home_city': 'Madrid', 'work_city': 'Madrid'}
The in operator checks dictionary keys, not values.
person = {
"name": "John",
"age": 25,
"city": "New York",
}
print("name" in person)True
print("John" in person)False
Use .values() if you need to search among the values.
print("John" in person.values())True
Without running the code, determine the result of each expression.
settings = {
"theme": "dark",
"language": "English",
"notifications": True,
}print("theme" in settings)print("dark" in settings)print("dark" in settings.values())The three results are True, False, and True.
Three useful methods provide views of a dictionary:
keys() returns the keys.values() returns the values.items() returns key-value pairs as tuples.product = {
"name": "Headphones",
"price": 79.99,
"stock": 14,
}
print(product.keys())dict_keys(['name', 'price', 'stock'])
print(product.values())dict_values(['Headphones', 79.99, 14])
print(product.items())dict_items([('name', 'Headphones'), ('price', 79.99), ('stock', 14)])
The update() method adds new pairs and replaces values for existing keys.
product.update({"price": 69.99, "colour": "black"})
print(product){'name': 'Headphones', 'price': 69.99, 'stock': 14, 'colour': 'black'}
A for loop over a dictionary visits its keys.
for key in product:
print(key)name
price
stock
colour
Use .items() when you need both the key and the value.
for key, value in product.items():
print(f"{key}: {value}")name: Headphones
price: 69.99
stock: 14
colour: black
Each loop contains one print() statement, even though it produces several output lines.
Use a loop and .items() to print each key and value in this format:
username: maya_21
level: 8
premium: True
profile = {
"username": "maya_21",
"level": 8,
"premium": True,
}for key, value in profile.items():
print(f"{key}: {value}")A dictionary can contain other dictionaries. This is useful when several records share the same structure.
students = {
"S001": {
"name": "Maya",
"programme": "Data Science",
"grade": 8.7,
},
"S002": {
"name": "Leo",
"programme": "Economics",
"grade": 7.9,
},
}
print(students){'S001': {'name': 'Maya', 'programme': 'Data Science', 'grade': 8.7}, 'S002': {'name': 'Leo', 'programme': 'Economics', 'grade': 7.9}}
Use one key for the outer dictionary and another for the nested dictionary.
print(students["S001"]["name"])Maya
print(students["S002"]["grade"])7.9
Using the students dictionary above:
9.1."graduated": False, to Leo’s record.students["S001"]["grade"] = 9.1
students["S002"]["graduated"] = Falseprint(students["S001"])print(students["S002"])The dict() function can convert a sequence of key-value pairs into a dictionary.
pairs = [
("name", "Pipo"),
("age", 10),
("city", "Seville"),
]
converted_dictionary = dict(pairs)
print(converted_dictionary){'name': 'Pipo', 'age': 10, 'city': 'Seville'}
Convert the following list of tuples into a dictionary. Then print the price of the salad.
menu_pairs = [
("soup", 6.50),
("salad", 8.00),
("pasta", 12.50),
]menu = dict(menu_pairs)print(menu["salad"])Create a dictionary that counts how many times each word appears in the list.
words = ["python", "data", "python", "model", "data", "python"]The expected dictionary is:
{"python": 3, "data": 2, "model": 1}word_counts = {}
for word in words:
word_counts[word] = word_counts.get(word, 0) + 1print(word_counts)| Data structure | Syntax | Preserves order | Mutable | Duplicate items | Access |
|---|---|---|---|---|---|
| List | [] |
Yes | Yes | Yes | Position |
| Tuple | () |
Yes | No | Yes | Position |
| Set | {item, ...} or set() |
No | Yes | No | Membership |
| Dictionary | {key: value} |
Yes | Yes | Keys: No; values: Yes | Key |
Use a list when position matters and the collection may change. Use a tuple when position matters and the collection should remain fixed. Use a set for unique items and membership tests. Use a dictionary when each value needs a meaningful identifier.
get() provides safe access to a missing key.keys(), values(), and items() provide different views of the data.Work through the “Dictionaries” homework exercises available here. To earn participation credit, complete the exercises highlighted in red.