Computer ScienceChapter 3: Programming Fundamentals
3.2.4 Dictionary
Dictionary
Explanation level
Introduction
A dictionary is an essential data structure in Python that is used to store and arrange data in an organized way using key-value pairs, such that each key represents a distinct value. In other words, each key is associated with a particular value. Lists have indexes, but in a dictionary, the key can be of any data type.
The textbook explains the concept using a phone book: in a phone book, the phone number (value) and the person's name (key) are associated with each other. By searching for the matching name, we may quickly get the phone number. Because of this fundamental idea, dictionaries may be used for storing and retrieving information by associating unique keys with values.
Definition
Dictionary is a data structure in Python that stores data as key-value pairs, where each key is unique and is associated with a specific value.
In simple words: A dictionary is like a real-life dictionary where you look up a word (key) to find its meaning (value). In Python, you look up a key to find its associated value.
Main Idea
- Name (key) → Phone number (value)
- Username (key) → Password (value)
- Student name (key) → Grade (value)
The textbook explains that for keys to be used for searching, they must be unchangeable types of data like strings, integers, or tuples. Values may store complicated data structures with flexibility since they can be any data type including texts, integers, lists, and even other dictionaries.
By design, dictionaries avoid duplicate keys such that every key acts as a unique label, hence avoiding reshuffling of data. Dictionaries maintain an ordered link among keys and their corresponding values, like keeping track of passwords and usernames, etc.
Core Concept
- Key-Value Pairs: Data is stored as pairs of keys and values.
- Unique Keys: Each key must be unique; duplicate keys are not allowed.
- Immutable Keys: Keys must be of an unchangeable data type (strings, integers, tuples).
- Any Data Type for Values: Values can be of any data type, including lists, other dictionaries, etc.
- Avoids Duplicate Keys: Every key acts as a unique label, avoiding reshuffling of data.
- Ordered Link: Dictionaries maintain an ordered link between keys and their corresponding values.
- Fast Lookup: Dictionaries are optimized for fast retrieval of values based on their keys.
Creating a Dictionary A dictionary is created by placing key-value pairs inside curly braces `{}`, separated by commas, with a colon `:` between each key and its value.
Example from the book (Fig. 3.5, lines 1–5): ```python student_grades = { 'Amir': 90, 'Bilal': 85, 'Dilawar': 92 } ``` This creates a dictionary where student names are keys and their grades are values.
Accessing Values Values are accessed using their keys inside square brackets `[]`.
Example from the book (lines 7–8): ```python for student, grade in student_grades.items(): print(f"{student}: {grade}") ``` Output (without line 13): ``` Amir: 90 Bilal: 85 Dilawar: 92 ```
Adding or Updating Entries You can add a new key-value pair or update an existing one by assigning a value to a key.
Example from the book (lines 10–11): ```python student_grades['Zaid'] = 88 # Add new entry student_grades['Bilal'] = 87 # Update existing entry ``` After these operations, the dictionary contains: ``` Amir: 90 Bilal: 87 Dilawar: 92 Zaid: 88 ```
Removing Entries The `del` statement removes a key-value pair from the dictionary.
Example from the book (line 13): ```python del student_grades['Dilawar'] ``` After this operation, the dictionary contains: ``` Amir: 90 Bilal: 87 Zaid: 88 ```
Note from the book: If line 13 is commented out, the record of 'Dilawar' will not be deleted. The textbook shows both outputs (with and without line 13) for better understanding.
Checking if a Key Exists The `in` operator checks if a key exists in the dictionary.
Example from the book (lines 15–18): ```python if 'Dilawar' in student_grades: print(f"\nDilawar's grade:", student_grades['Dilawar'], "\n") else: print("Student Dilawar not found \n") ``` Output (after deletion): ``` Student Dilawar not found ```
Iterating Through a Dictionary The `items()` method returns key-value pairs, which can be used in a loop.
Example from the book (lines 20–21): ```python for student, grade in student_grades.items(): print(f"{student}: {grade}") ``` Output: ``` Amir: 90 Bilal: 87 Zaid: 88 ```
- In lists, we need to go through each item individually to locate what you're searching for.
- In dictionaries, using the key-value pair, we can locate the searching item quickly.
Example from the book (Fig. 3.7): A program was written where a list and dictionary were randomly populated with 1 lakh entries. Such that a list of strings of 4-characters was set up while for every 4-character in the dictionary a corresponding key value was randomly arranged. Next, 1 random element was searched in both the programming constructs and their times were noted. The difference of time clearly shows the searching in dictionary is faster as compared to the list.
Sample output from the book: ``` Search results (Dictionary): {20145: 'dlei'} Search results (List): ['uiib'] Dictionary search time: 1.000166 msec List search time: 3.000259 msec Difference of time: Dictionary Time - List Time: -2.000093 msec ```
Empty Dictionary and Adding Entries The textbook also shows how to create an empty dictionary and add entries later.
Example from the book (Fig. 3.6): ```python studenttestnumber = {} while True: name = input("Enter student name (or 'q' to quit): ") if name.lower() == 'q': break grade = float(input(f"Enter Test-Number for {name}: ")) studenttestnumber[name] = grade
name = input("Enter student name to view test-number: ") if name in studenttestnumber: print(f"{name}'s test-number: {studenttestnumber[name]}") else: print(f"Student '{name}' not found.") ```
Sample output from the book: ``` Enter student name (or 'q' to quit): Amir Enter Test-Number for Amir: 90 Enter student name (or 'q' to quit): Bilal Enter Test-Number for Bilal: 87 Enter student name (or 'q' to quit): Dilawar Enter Test-Number for Dilawar: 92 Enter student name (or 'q' to quit): Zaid Enter Test-Number for Zaid: 88 Enter student name (or 'q' to quit): q Enter student name to view test-number: Bilal Bilal's test-number: 87.0 ```
Activity 2 (from the book) The textbook provides an activity: "Extend the program of Fig 3.5 in such a way that if the searched item is not found in the dictionary, ask the user if it needs to be added. If user presses 'y' for yes, then the key and respective value (to be taken input) are to be added."
Intermediate Level
Dictionaries are different from lists, tuples, and sets in important ways:
| Feature | List | Tuple | Set | Dictionary |
|---|---|---|---|---|
| Structure | Ordered collection | Ordered collection | Unordered collection | Key-value pairs |
| Access | By index | By index | By value (in operator) | By key |
| Duplicates | Allowed | Allowed | Not allowed | Keys must be unique |
| Mutability | Mutable | Immutable | Mutable | Mutable |
| Syntax | `[]` | `()` | `{}` | `{}` with key: value |
| Search Speed | Slower | Slower | Fast (in operator) | Fast (key lookup) |
The textbook emphasizes that dictionaries are faster for searching because they use keys instead of indexes. This makes them ideal for tasks like looking up a student's grade by name.
Important Points
- - Dictionary: A data structure that stores data as key-value pairs.
- - Keys must be unique: Duplicate keys are not allowed.
- - Keys must be immutable: Strings, integers, tuples (not lists).
- - Values can be any type: Numbers, strings, lists, other dictionaries.
- - Access values by key: Use `dictionary[key]`.
- - Add/Update: Assign a value to a key: `dictionary[key] = value`.
- - Remove: Use `del dictionary[key]`.
- - Check if key exists: Use `key in dictionary`.
- - Iterate: Use `dictionary.items()` to get key-value pairs.
- - Faster than lists for searching: Key-based lookup is faster than index-based or value-based search.
- - Empty dictionary: `{}` — can be populated later.
- - Activity 2: Extend the program to add a missing entry if the user agrees.
Remember
- - Dictionary = Key-value pairs.
- - Keys must be unique.
- - Keys must be immutable (strings, integers, tuples).
- - Access by key: `dictionary[key]`.
- - Add/Update: `dictionary[key] = value`.
- - Remove: `del dictionary[key]`.
- - Check key: `key in dictionary`.
- - Iterate: `dictionary.items()`.
- - Faster than lists for searching.
- - Syntax: `{}` with `key: value`.
- - Activity 2: Add missing entries if the user agrees.
Common Mistakes
- 1. Trying to use a list as a key — Keys must be immutable; lists are mutable and cannot be used as keys.
- 2. Forgetting that keys are unique — If you assign a value to an existing key, it updates the value rather than adding a new entry.
- 3. Trying to access a non-existent key — This raises a `KeyError`. Use `in` to check first.
- 4. Confusing dictionaries with sets — Both use `{}`, but dictionaries store key-value pairs, while sets store single values.
- 5. Thinking dictionaries are unordered — In Python 3.7 and later, dictionaries maintain insertion order.
- 6. Using a dictionary when order matters more than lookup speed — If you need strict ordering and index-based access, use a list.
- 7. Trying to use a mutable value as a key — Keys must be immutable; lists, sets, and other dictionaries cannot be used as keys.
Quick Revision
- Dictionary: A data structure that stores data as key-value pairs. Each key is unique and is associated with a specific value.
- Key characteristics:
- Keys must be unique.
- Keys must be unchangeable types (strings, integers, tuples).
- Values can be any data type.
- Dictionaries are mutable.
- Dictionaries maintain an ordered link among keys and values.
- Common operations:
- Create: `student_grades = {'Amir': 90, 'Bilal': 85, 'Dilawar': 92}`
- Access: `student_grades['Amir']` → `90`
- Add/Update: `student_grades['Zaid'] = 88`
- Remove: `del student_grades['Dilawar']`
- Check key: `'Amir' in student_grades` → `True`
- Iterate: `for student, grade in student_grades.items():`
- Advantage: Faster search than lists (key-based lookup).
- Use cases: Phone books, student records, username-password storage.
- Empty dictionary: `{}` — can be populated later.
- Activity 2: Extend the program to add missing entries if the user agrees.
60-Second Revision
- Dictionary = Key-value pairs.
- Keys must be unique.
- Keys must be immutable.
- Access by key: `dictionary[key]`.
- Add/Update: `dictionary[key] = value`.
- Remove: `del dictionary[key]`.
- Check key: `key in dictionary`.
- Iterate: `dictionary.items()`.
- Faster than lists for searching.
- Warning: Lists cannot be used as keys (they are mutable).
Frequently Asked Questions (FAQs)
Q1. What is a dictionary in Python? Answer: A dictionary is a data structure in Python that stores data as key-value pairs, where each key is unique and is associated with a specific value. Dictionaries are used for storing and retrieving information by associating unique keys with values.
Q2. How do you create a dictionary? Answer: A dictionary is created by placing key-value pairs inside curly braces `{}`, separated by commas, with a colon `:` between each key and its value. For example, `student_grades = {'Amir': 90, 'Bilal': 85, 'Dilawar': 92}`.
- Q3. How do you access a value in a dictionary?
- Answer: Values are accessed using their keys inside square brackets `[]`. For example, `student_grades['Amir']` returns `90`.
Q4. How do you add or update an entry in a dictionary? Answer: You can add a new key-value pair or update an existing one by assigning a value to a key. For example, `student_grades['Zaid'] = 88` adds a new entry, and `student_grades['Bilal'] = 87` updates an existing entry.
- Q5. How do you remove an entry from a dictionary?
- Answer: Use the `del` statement. For example, `del student_grades['Dilawar']` removes the entry with the key `'Dilawar'`.
- Q6. How do you check if a key exists in a dictionary?
- Answer: Use the `in` operator. For example, `'Amir' in student_grades` returns `True` if `'Amir'` is a key in the dictionary.
- Q7. How do you iterate through a dictionary?
- Answer: Use the `items()` method to get key-value pairs. For example:
- ```python
- for student, grade in student_grades.items():
- print(f"{student}: {grade}")
- ```
Q8. Why is a dictionary faster than a list for searching? Answer: Dictionaries use keys for direct lookup, which is much faster than searching through a list element by element. In a list, you need to go through each item individually to locate what you're searching for. In a dictionary, the key directly points to the value, making retrieval almost instantaneous.
- Q9. What data types can be used as keys in a dictionary?
- Answer: Keys can be of any unchangeable data type, such as strings, integers, or tuples. Lists cannot be used as keys because they are mutable.
- Q10. What happens if you try to access a key that does not exist in the dictionary?
- Answer: Accessing a non-existent key raises a `KeyError`. To avoid this, use the `in` operator to check if the key exists before accessing it.
Q11. What is Activity 2 in the textbook? Answer: Activity 2 asks students to extend the program of Fig 3.5 in such a way that if the searched item is not found in the dictionary, ask the user if it needs to be added. If the user presses 'y' for yes, then the key and respective value (to be taken input) are to be added.
- Dictionary search time: 1.000166 msec
- List search time: 3.000259 msec
- Difference: Dictionary is faster by about 2 msec.
Practice Questions
Short Response Questions (SRQs)
- Define a dictionary in Python and explain its key characteristics.
- How do you create a dictionary? Give an example.
- How do you access a value in a dictionary?
- Explain how to add, update, and remove entries in a dictionary.
- Why is a dictionary faster than a list for searching?
Extended Response Questions (ERQs)
- Discuss the characteristics of dictionaries in Python. Why are they considered ideal for storing key-value pairs?
- Compare and contrast dictionaries with lists, tuples, and sets in Python. In what situations would you choose one over the others?
- Explain the operations that can be performed on dictionaries (access, add, update, remove, check key, iterate) with examples.
- Analyze the importance of dictionaries in Python programming. Provide real-world examples of when dictionaries are the appropriate data structure.
- You are writing a Python program to store student records (name and grade). Explain why you would use a dictionary instead of a list, and demonstrate how to create, update, and retrieve records.
- Extend the program of Fig. 3.5 to add a missing entry if the user agrees (Activity 2). Write the complete code and explain the steps.
Multiple Choice Questions (MCQs)
- Q1. What is a dictionary in Python?
- A. An ordered collection of items
- B. A collection of unique and unordered elements
- C. A collection of key-value pairs
- D. A type of function
- Correct Answer: C
- Explanation: A dictionary is a collection of key-value pairs.
- Q2. How is a dictionary created?
- A. Using square brackets `[]`
- B. Using curly braces `{}`
- C. Using parentheses `()`
- D. Using angle brackets `<>`
- Correct Answer: B
- Explanation: Dictionaries are created using curly braces `{}`.
- Q3. Which of the following is true about dictionary keys?
- A. Keys can be duplicated
- B. Keys must be unique
- C. Keys must be integers
- D. Keys cannot be strings
- Correct Answer: B
- Explanation: Keys in a dictionary must be unique; duplicate keys are not allowed.
- Q4. How do you access a value in a dictionary?
- A. Using an index: `dictionary[0]`
- B. Using the key: `dictionary['key']`
- C. Using the `get()` method only
- D. Using the `find()` method
- Correct Answer: B
- Explanation: Values are accessed using their keys: `dictionary['key']`.
- Q5. How do you add or update an entry in a dictionary?
- A. Using `append()`
- B. Using `insert()`
- C. Assigning a value to a key: `dictionary[key] = value`
- D. Using `add()`
- Correct Answer: C
- Explanation: You add or update an entry by assigning a value to a key: `dictionary[key] = value`.
- Q6. How do you remove an entry from a dictionary?
- A. Using `remove()`
- B. Using `pop()`
- C. Using `del dictionary[key]`
- D. Using `delete()`
- Correct Answer: C
- Explanation: The `del` statement removes a key-value pair: `del dictionary[key]`.
- Q7. How do you check if a key exists in a dictionary?
- A. Using the `in` operator
- B. Using the `exists()` function
- C. Using the `find()` function
- D. Using the `check()` function
- Correct Answer: A
- Explanation: The `in` operator checks if a key exists in a dictionary.
- Q8. Which method is used to iterate through key-value pairs in a dictionary?
- A. `keys()`
- B. `values()`
- C. `items()`
- D. `pairs()`
- Correct Answer: C
- Explanation: The `items()` method returns key-value pairs for iteration.
- Q9. Why is a dictionary faster than a list for searching?
- A. Because dictionaries use keys for direct lookup
- B. Because dictionaries are ordered
- C. Because dictionaries allow duplicates
- D. Because dictionaries use indexes
- Correct Answer: A
- Explanation: Dictionaries use keys for direct lookup, which is faster than searching through a list element by element.
- Q10. What happens if you try to access a key that does not exist in a dictionary?
- A. It returns `None`
- B. It raises a `KeyError`
- C. It returns `0`
- D. It creates a new key
- Correct Answer: B
- Explanation: Accessing a non-existent key raises a `KeyError`.
- Q11. What is Activity 2 in the textbook?
- A. Add a missing entry if the user agrees
- B. Search for all odd numbers and remove them
- C. Calculate the average of a list
- D. Sort the list in descending order
- Correct Answer: A
- Explanation: Activity 2 asks students to extend the program to add a missing entry if the user agrees.
- Q12. Which of the following can be used as a dictionary key?
- A. A list
- B. A set
- C. A tuple
- D. A dictionary
- Correct Answer: C
- Explanation: Keys must be immutable, so tuples can be used as keys, but lists, sets, and dictionaries cannot.
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.4 Dictionary
Sticky Notes · Quick Revision
Key Point 1
- Dictionary = Key-value pairs.
Key Point 2
- Keys must be unique.
Key Point 3
- Keys must be immutable (strings, integers, tuples).
Key Point 4
- Access by key: `dictionary[key]`.
Key Point 5
- Add/Update: `dictionary[key] = value`.
Key Point 6
- Remove: `del dictionary[key]`.
Key Point 7
- Check key: `key in dictionary`.
Key Point 8
- Iterate: `dictionary.items()`.
Key Point 9
- Faster than lists for searching.
Key Point 10
- Syntax: `{}` with `key: value`.
Same supplied content as this Notes page (shared canonical source).