Welcome! Today, we're diving into Python dictionaries. These store items as key-value pairs, much like a real dictionary where you look up a word (key) to find its meaning (value). By the end of this lesson, you’ll have a good grasp of dictionaries.
Dictionaries in Python are unordered collections of data values. This differentiation sets them apart from lists
and tuples
, which have specific orders. In a dictionary, each item possesses a key
associated with a specific value
, enhancing its efficiency in data access and management.
Here's a simple dictionary:
In dictionary_example
, the keys are "Alice", "Bob", and "Charlie", and the values are 25, 28, and 30, respectively. Key uniqueness is integral to the design of dictionaries - for example, that means we can only have a single key called "Alice"
.
Dictionaries are initiated by placing key-value pairs within {}
. Another way to create a dictionary is by using a dict()
method.
Keys and values can be of different data types.
Unlike lists, dictionaries are collections of items accessed by their keys, not by their positions.
get()
is a safer method for retrieving values as it returns None
or a default value if the key is nonexistent.
To check whether the key exists in the dictionary, use the in
operator:
Python dictionaries are mutable, meaning we can add, modify, or delete elements.
We can add a new key-value pair like this:
Here's how to modify a value in a dictionary:
Here's how to delete a key-value pair:
Python dictionaries provide several handy methods, like keys()
, values()
, and items()
.
It isn't uncommon to nest dictionaries within other dictionaries, forming what we call nested dictionaries.
Nested dictionaries can be manipulated similarly to simple dictionaries.
Great work! We've delved into Python dictionaries: understanding their structure, creating and using them, and exploring their real-life applications. Next, let's reinforce this knowledge with some hands-on exercises!
