Accessing Dictionary Elements
To retrieve a specific value in a dictionary, use its key inside square brackets. For instance, to obtain Sarah’s username:Attempting to access a key that does not exist in the dictionary will raise a KeyError.
Common Dictionary Methods
Python dictionaries come with several built-in methods that simplify data handling. The key methods include:- keys(): Returns an iterable view of all the keys.
- values(): Returns an iterable view of all the values.
- items(): Returns an iterable view of key-value pairs as tuples.
Iterating Over Dictionaries
You can iterate over all key-value pairs using a loop. For example, to print each key alongside its corresponding value, you can use the following approaches: Using thekeys() method:
items() method:
values() method:
Modifying a Dictionary
You can easily update, add, or remove elements from a dictionary. Below are some common operations:Updating Values
To update an existing value, reference the key and assign a new value. For example, to update Max’s username:Adding a New Key-Value Pair
To add a new entry, such as adding a user named Chloe with the username “chloe123”, you can use theupdate() method:
Deleting an Entry
If you need to remove an entry (for example, deleting Max’s account), use thedel statement:
clear() method. For removing and returning the last inserted item, the popitem() method is available.
Copying a Dictionary
To create a shallow copy of a dictionary, you can use thecopy() method: