1 Answers
π Understanding Python Dictionaries
In Python, a dictionary is a collection of key-value pairs. Think of it like a real-world dictionary, where you have a word (the key) and its definition (the value). Each key in a dictionary must be unique, but the values can be anything β numbers, strings, lists, or even other dictionaries!
π A Brief History
Dictionaries were introduced into Python to provide a way to store and retrieve data using meaningful keys rather than just numerical indexes. This was inspired by the concept of associative arrays found in other programming languages. The use of dictionaries greatly enhances code readability and efficiency in many applications.
π Key Principles
- π Keys must be immutable: Keys can be strings, numbers, or tuples, but not lists.
- π Values can be anything: Values can be any Python data type.
- β±οΈ Dictionaries are mutable: You can add, remove, or modify key-value pairs after the dictionary is created.
β Adding Key-Value Pairs
There are a couple of ways to add key-value pairs to a Python dictionary:
- π» Using square bracket notation: This is the most common and straightforward method.
- βοΈ Using the
update()method: This method is useful for adding multiple key-value pairs at once or merging dictionaries.
π» Square Bracket Notation
To add a key-value pair using square bracket notation, you simply assign a value to a new key:
my_dict = {}
my_dict['name'] = 'Alice'
my_dict['age'] = 16
print(my_dict) # Output: {'name': 'Alice', 'age': 16}
βοΈ The update() Method
The update() method adds key-value pairs from another dictionary or an iterable of key-value pairs:
my_dict = {}
my_dict.update({'city': 'New York', 'grade': 10})
print(my_dict) # Output: {'city': 'New York', 'grade': 10}
# Using a list of tuples:
my_dict.update([('subject', 'Math'), ('teacher', 'Mr. Smith')])
print(my_dict) # Output: {'city': 'New York', 'grade': 10, 'subject': 'Math', 'teacher': 'Mr. Smith'}
π Real-World Example: Student Database
Let's create a simple student database using a dictionary:
student = {
'name': 'Bob',
'age': 15,
'grade': 9
}
# Adding more information
student['school'] = 'High School'
student['subjects'] = ['Math', 'Science', 'English']
print(student)
# Output: {'name': 'Bob', 'age': 15, 'grade': 9, 'school': 'High School', 'subjects': ['Math', 'Science', 'English']}
π Practice Quiz
- β Create an empty dictionary called
bookand add the following key-value pairs:title(The Hitchhiker's Guide to the Galaxy),author(Douglas Adams), andyear(1979). - β Add a key-value pair to the
bookdictionary from the previous question:genre(Science Fiction). - π» Given the dictionary
phone = {'brand': 'Samsung', 'model': 'S21'}, use theupdate()method to add{'color': 'black', 'storage': '128GB'}. - π‘ Explain why keys in a Python dictionary must be immutable.
- π What happens if you try to add a key that already exists in the dictionary? Provide an example.
- π Can you use a list as a key in a Python dictionary? Explain why or why not.
- π§ͺ Create a dictionary representing a science experiment with keys like
experiment_name,date, andresults. Add sample values.
β Conclusion
Adding key-value pairs to Python dictionaries is a fundamental skill. Whether you use square bracket notation or the update() method, understanding how to manipulate dictionaries is crucial for many programming tasks. Keep practicing, and you'll master it in no time!
Join the discussion
Please log in to post your answer.
Log InEarn 2 Points for answering. If your answer is selected as the best, you'll get +20 Points! π