Computer ScienceChapter 3: Programming Fundamentals
3.2.6 List as a Value in Dictionary
List as a Value in Dictionary
Explanation level
Introduction
A dictionary comprises key-value pairs, and multiple values against a key can be stored in the dictionary in the form of a list. This is a powerful combination that allows you to associate one key with multiple pieces of information.
The textbook explains that every record of a student can be stored in a dictionary such that the student's name will act as the key while the registration number and marks will be the values. To store multiple values, a list can be used.
Definition
List as a Value in Dictionary means using a list as the value in a key-value pair, allowing multiple items to be stored under a single key.
In simple words: Instead of storing just one value for a key, you can store a whole list of values. This lets you group related information together under one label.
Main Idea
The core idea is grouping: one key can be associated with multiple values by using a list. This is useful when a single entity (like a student) has multiple pieces of data (like registration number, marks in different subjects, etc.).
- Key: Student name (e.g., "Sara", "Jamal", "Zaid").
- Value: A list containing the registration number and marks (e.g., `["345", 85, 90, 78]`).
This structure allows you to store and retrieve all information about a student using just their name.
Core Concept
Creating a Dictionary with Lists as Values A dictionary with lists as values is created by placing lists inside the dictionary as values.
Example from the book (Fig. 3.10, lines 1–5): ```python students = { "Sara": ["345", 85, 90, 78], "Jamal": ["678", 75, 88, 92], "Zaid": ["912", 80, 79, 95] } ```
- Each key is a student's name (string).
- Each value is a list containing:
- Registration number (string) at index 0.
- Marks for subject 1 at index 1.
- Marks for subject 2 at index 2.
- Marks for subject 3 at index 3.
Accessing Values from a List in a Dictionary To access a specific value, you use the key to get the list, then the index to get the specific element.
Example from the book (lines 7–8): ```python sara_reg_num = students["Sara"][0] print("Sara's Reg. No.:", sara_reg_num) ``` Output from the book: `Sara's Reg. No.: 345`
Example from the book (lines 9–10): ```python jamal_marks = students["Jamal"][1] print("Jamal's Marks for first subject are:", jamal_marks) ``` Output from the book: `Jamal's Marks for first subject are: 75`
- `students["Sara"]` returns the list `["345", 85, 90, 78]`.
- `students["Sara"][0]` returns the first element of that list, which is `"345"`.
Adding a New Record You can add a new record by assigning a list to a new key.
Example from the book (line 12): ```python students["Azra"] = ["234", 78, 85, 90] ``` This adds a new student "Azra" with registration number "234" and marks 78, 85, 90.
Output from the book (line 13): ```python print(students, "\n") ``` Output: ``` {'Sara': ['345', 85, 90, 78], 'Jamal': ['678', 75, 88, 92], 'Zaid': ['912', 80, 79, 95], 'Azra': ['234', 78, 85, 90]} ```
Updating a Value in the List To update a specific value, you access the list using the key and index, then assign a new value.
Example from the book (lines 15–19): ```python student_name = "Azra" subject_index = 2 new_mark = 100 if student_name in students: students[student_name][subject_index] = new_mark print(f"*** Marks updated for {student_name} at index {subject_index} ***\n") else: print(f"Student not found\n") ``` Output from the book: `*** Marks updated for Azra at index 2 ***`
- `students["Azra"]` returns the list `["234", 78, 85, 90]`.
- `students["Azra"][2] = 100` changes the third element (index 2) from 85 to 100.
- The list becomes `["234", 78, 100, 90]`.
Iterating Through the Dictionary The textbook shows how to iterate through the dictionary and print each student's details.
Example from the book (lines 24–28): ```python for name, details in students.items(): print(f"Name: {name}") print(f"Registration Number: {details[0]}") print(f"Marks: {details[1]}, {details[2]}, {details[3]}") ```
Output: ``` Name: Sara Registration Number: 345 Marks: 85, 90, 78 Name: Jamal Registration Number: 678 Marks: 75, 88, 92 Name: Zaid Registration Number: 912 Marks: 80, 79, 95 Name: Azra Registration Number: 234 Marks: 78, 100, 90 ```
- One key, multiple values: A list allows multiple values to be stored under a single key.
- Index-based access: To access a specific value, use the key to get the list, then the index to get the element.
- Flexible: The list can contain any data type (strings, integers, etc.).
- Mutable: Both the dictionary and the list can be modified.
- Grouping: Related information is grouped together under one key.
Activity 5 (from the book) The textbook provides an activity: "A primary school has subject teachers such that a teacher teaches only 2 subjects to a class. Assuming, each class studies 8 subjects in total. Write a program using list as a value in dictionary, so that 'class' becomes the key and respective 'teachers' are stored as values."
Intermediate Level
Using a list as a value in a dictionary is different from using a simple value:
| Feature | Simple Value | List as Value |
|---|---|---|
| Structure | `{"Sara": 85}` | `{"Sara": ["345", 85, 90, 78]}` |
| Access | `students["Sara"]` → `85` | `students["Sara"][0]` → `"345"` |
| Multiple values | No | Yes |
| Grouping | Limited | Related data grouped together |
| Use case | Single attribute | Multiple attributes per key |
- Access individual values using two levels of indexing: `students["Sara"][0]`.
- Update individual values: `students["Azra"][2] = 100`.
- Iterate through all records and print details.
Important Points
- - List as a value in dictionary: Allows multiple values to be stored under a single key.
- - Access: Use the key to get the list, then the index to get the value: `dictionary[key][index]`.
- - Add a record: Assign a list to a new key: `dictionary[key] = [value1, value2, ...]`.
- - Update a value: Use the key and index to assign a new value: `dictionary[key][index] = new_value`.
- - Iterate: Use `items()` to get key-value pairs, then access list elements by index.
- - Check key exists: Use `if key in dictionary:` before accessing or updating.
- - Use cases: Student records, employee data, product details.
- - Activity 5: Use class as key and teachers as values in a dictionary.
Remember
- - List as Value = Multiple values under one key.
- - Access: `dictionary[key][index]`.
- - Add: `dictionary[key] = [list of values]`.
- - Update: `dictionary[key][index] = new_value`.
- - Iterate: `for key, values in dictionary.items():`
- - Check key: `if key in dictionary:`
- - Use for records: Students, employees, products.
- - Activity 5: Class → Teachers.
Common Mistakes
- 1. Forgetting the index when accessing a value — `dictionary[key]` returns the entire list, not a single value. Use `dictionary[key][index]` for a specific value.
- 2. Trying to update a value without checking if the key exists — This can raise a `KeyError`. Use `if key in dictionary:` first.
- 3. Confusing the order of indexes — The first index is for the key, the second is for the list element.
- 4. Trying to use a list as a key — Lists are mutable and cannot be used as keys. Use immutable types (strings, integers, tuples) as keys.
- 5. Thinking all values in the list must be the same type — Lists can contain different data types (e.g., string registration number, integer marks).
- 6. Forgetting that the list is mutable — Changes to the list affect the dictionary.
Quick Revision
- - List as a Value in Dictionary: A dictionary can store multiple values under a single key by using a list as the value.
- - Creating:
- ```python
- students =
- "Sara": ["345", 85, 90, 78],
- "Jamal": ["678", 75, 88, 92],
- "Zaid": ["912", 80, 79, 95]
- }
- ```
- - Accessing values:
- - `students["Sara"]` → `["345", 85, 90, 78]`
- - `students["Sara"][0]` → `"345"`
- - `students["Sara"][1]` → `85`
- - Adding a record: `students["Azra"] = ["234", 78, 85, 90]`
- - Updating a value: `students["Azra"][2] = 100`
- - Iterating:
- ```python
- for name, details in students.items():
- print(f"Name: {name}")
- print(f"Registration Number: {details[0]}")
- print(f"Marks: {details[1]}, {details[2]}, {details[3]}")
- ```
- - Use case: Storing student records, employee data, product details.
- - Activity 5: Use class as key and teachers as values.
60-Second Revision
- List as Value = Multiple values under one key.
- Access: `dictionary[key][index]`.
- Add: `dictionary[key] = [list of values]`.
- Update: `dictionary[key][index] = new_value`.
- Iterate: `for key, values in dictionary.items():`
- Check key: `if key in dictionary:`
- Warning: Use two indexes to access a specific value.
Frequently Asked Questions (FAQs)
Q1. What does it mean to use a list as a value in a dictionary? Answer: It means that instead of storing a single value for a key, you store a list of values. This allows multiple pieces of information to be grouped under a single key. For example, `students = "Sara": ["345", 85, 90, 78]` stores Sara's registration number and marks in a list.
Q2. How do you access a specific value from a list in a dictionary? Answer: Use the key to get the list, then the index to get the specific value. For example, `students["Sara"][0]` returns the first element of Sara's list (`"345"`).
- Q3. How do you add a new record to a dictionary with lists as values?
- Answer: Assign a new list to a new key. For example, `students["Azra"] = ["234", 78, 85, 90]` adds a new student "Azra" with the specified values.
Q4. How do you update a specific value in a list within a dictionary? Answer: Access the list using the key, then use the index to assign a new value. For example, `students["Azra"][2] = 100` updates the third element of Azra's list.
- Q5. How do you iterate through a dictionary with lists as values?
- Answer: Use the `items()` method to get key-value pairs, then access the list elements by index. For example:
- ```python
- for name, details in students.items():
- print(f"Name: {name}")
- print(f"Registration Number: {details[0]}")
- print(f"Marks: {details[1]}, {details[2]}, {details[3]}")
- ```
- Q6. Why is it important to check if a key exists before updating a value?
- Answer: If the key does not exist, trying to update a value will raise a `KeyError`. Using `if key in dictionary:` before updating prevents this error.
- Q7. Can the list in a dictionary contain different data types?
- Answer: Yes, the list can contain different data types. For example, `["345", 85, 90, 78]` contains a string (registration number) and integers (marks).
- Student records (name → registration number, marks).
- Employee data (employee ID → name, department, salary).
- Product details (product ID → name, price, quantity).
- Contact information (name → phone numbers, email addresses).
Q9. What is the advantage of using a list as a value in a dictionary? Answer: The advantage is grouping: related information can be stored together under a single key. This makes it easier to manage and retrieve all information about a particular entity (like a student or employee) using just one key.
- Each key is like a primary key (unique identifier).
- Each list is like a row of data (multiple attributes).
- Each element in the list is like a column value.
Q11. What is Activity 5 in the textbook? Answer: Activity 5 asks students to write a program using a list as a value in a dictionary, where the 'class' becomes the key and the respective 'teachers' are stored as values. For example: ```python teachers = { "Class 1": ["Teacher A", "Teacher B"], "Class 2": ["Teacher C", "Teacher D"], "Class 3": ["Teacher E", "Teacher F"] } ```
Practice Questions
Short Response Questions (SRQs)
- Explain how a list can be used as a value in a dictionary.
- How do you access a specific value from a list in a dictionary?
- How do you add a new record to a dictionary with lists as values?
- How do you update a specific value in a list within a dictionary?
- Why is it important to check if a key exists before updating a value?
Extended Response Questions (ERQs)
- Discuss the concept of using a list as a value in a dictionary. Why is this useful for storing records?
- Explain how to create, access, and modify a dictionary with lists as values. Provide examples.
- Analyze the importance of iterating through a dictionary with lists as values. How can this be used to display student records?
- You are writing a Python program to store student records (name, registration number, and marks for three subjects). Describe how you would use a dictionary with lists as values to store, access, and update the records.
- Compare and contrast a dictionary with lists as values with a simple dictionary. In what situations would you choose one over the other?
- Write a program for Activity 5: Use class as key and teachers as values in a dictionary. Explain the steps.
Multiple Choice Questions (MCQs)
- Q1. What is a list as a value in a dictionary?
- A. A dictionary with only one value per key
- B. A dictionary where the value is a list, allowing multiple values per key
- C. A list that contains dictionaries
- D. A dictionary that cannot be modified
- Correct Answer: B
- Explanation: A list as a value in a dictionary allows multiple values to be stored under a single key.
- Q2. How do you access the first element of a list stored as a value in a dictionary?
- A. `dictionary[key][0]`
- B. `dictionary[0][key]`
- C. `dictionary[key]`
- D. `dictionary[0]`
- Correct Answer: A
- Explanation: Use `dictionary[key][0]` to access the first element of the list.
- Q3. How do you add a new record to a dictionary with lists as values?
- A. `dictionary.append(key, list)`
- B. `dictionary[key] = list`
- C. `dictionary.insert(key, list)`
- D. `dictionary.add(key, list)`
- Correct Answer: B
- Explanation: Assign a list to a new key: `dictionary[key] = list`.
- Q4. How do you update the second element of a list stored as a value in a dictionary?
- A. `dictionary[key][2] = newvalue`
- B. `dictionary[key][1] = newvalue`
- C. `dictionary[1][key] = newvalue`
- D. `dictionary[key] = newvalue`
- Correct Answer: B
- Explanation: Index 1 refers to the second element: `dictionary[key][1] = newvalue`.
- Q5. What is the output of the following code?
- ```python
- students = "Sara": ["345", 85, 90, 78]
- print(students["Sara"][1])
- ```
- A. "345"
- B. 85
- C. 90
- D. 78
- Correct Answer: B
- Explanation: `students["Sara"][1]` accesses the second element of the list, which is `85`.
- Q6. Which method is used to iterate through a dictionary with lists as values?
- A. `keys()`
- B. `values()`
- C. `items()`
- D. `pairs()`
- Correct Answer: C
- Explanation: The `items()` method returns key-value pairs for iteration.
- Q7. Why should you check if a key exists before updating a value?
- A. To avoid a `KeyError`
- B. To make the code run faster
- C. To add a new key
- D. To delete the key
- Correct Answer: A
- Explanation: Checking if the key exists prevents a `KeyError` when updating.
- Q8. What data types can a list in a dictionary contain?
- A. Only integers
- B. Only strings
- C. Any data type
- D. Only lists
- Correct Answer: C
- Explanation: A list in a dictionary can contain any data type.
- Q9. Which of the following is a real-world use case for a list as a value in a dictionary?
- A. Storing a single student's name
- B. Storing a student's registration number and marks
- C. Storing a single integer
- D. Storing a single string
- Correct Answer: B
- Explanation: Storing a student's registration number and marks is a real-world use case for a list as a value in a dictionary.
- Q10. What is the output of the following code?
- ```python
- students = "Sara": ["345", 85, 90, 78]
- students["Sara"][2] = 100
- print(students["Sara"])
- ```
- A. `["345", 85, 90, 78]`
- B. `["345", 85, 100, 78]`
- C. `["345", 100, 90, 78]`
- D. `["345", 85, 90, 100]`
- Correct Answer: B
- Explanation: `students["Sara"][2] = 100` updates the third element (index 2) to 100, resulting in `["345", 85, 100, 78]`.
- Q11. What is Activity 5 in the textbook?
- A. Store student records
- B. Use class as key and teachers as values
- C. Calculate the average of a list
- D. Sort the dictionary
- Correct Answer: B
- Explanation: Activity 5 asks students to use class as key and teachers as values in a dictionary.
Did you understand this topic?
Your answer is saved with your learning record. It does not mark the topic as mastered.
Quick revision
Revision Zone
Review the key facts, formulas and checks before you move on.3.2.6 List as a Value in Dictionary
Sticky Notes · Quick Revision
Key Point 1
- List as Value = Multiple values under one key.
Key Point 2
- Access: `dictionary[key][index]`.
Key Point 3
- Add: `dictionary[key] = [list of values]`.
Key Point 4
- Update: `dictionary[key][index] = new_value`.
Key Point 5
- Iterate: `for key, values in dictionary.items():`
Key Point 6
- Check key: `if key in dictionary:`
Key Point 7
- Use for records: Students, employees, products.
Key Point 8
- Activity 5: Class → Teachers.
Same supplied content as this Notes page (shared canonical source).