Python Dictionaries Explained
Introduction to Dictionaries
The Power of Pairs
Imagine a real-world dictionary. You don't read it from cover to cover to find a word. Instead, you look up a specific word (a key) to find its definition (a value). Python dictionaries work in a very similar way.
A dictionary is a data structure that stores information in key-value pairs. Each key is unique and is used to retrieve its corresponding value. This makes them incredibly efficient for looking up data when you know the identifier you're looking for.
Think of a dictionary as a collection of labels, where each label points to a piece of information.
Creating a Dictionary
You create a dictionary using curly braces {}. Inside, you list your key-value pairs, with a colon : separating the key from its value. Each pair is separated by a comma.
# A simple dictionary for a user's profile
user_profile = {
"name": "Alex",
"age": 32,
"city": "San Francisco"
}
print(user_profile)
# Output: {'name': 'Alex', 'age': 32, 'city': 'San Francisco'}
In this example:
"name","age", and"city"are the keys. Keys are typically strings, but they can be other immutable types like numbers."Alex",32, and"San Francisco"are the values. Values can be any data type: strings, numbers, booleans, or even other data structures like lists.
Looking Up Values
To get a value from a dictionary, you use square brackets [] with the key inside. This is similar to accessing elements in a list, but instead of an index number, you use the unique key.
# Accessing the value associated with the 'name' key
user_name = user_profile["name"]
print(user_name)
# Output: Alex
# Accessing the value for 'age'
user_age = user_profile["age"]
print(user_age)
# Output: 32
This direct lookup is what makes dictionaries so fast and useful. Be careful, though. If you try to access a key that doesn't exist in the dictionary, Python will raise an error.
Dictionaries vs. Lists
While both dictionaries and lists store collections of data, they serve different purposes and have key distinctions.
| Feature | List | Dictionary |
|---|---|---|
| Structure | Ordered sequence of items | Unordered collection of key-value pairs |
| Access | By numerical index (e.g., my_list[0]) | By unique key (e.g., my_dict['name']) |
| Best For | Storing an ordered collection | Storing related pieces of information; quick lookups |
Use a list when the order of items matters, like a to-do list or a sequence of steps. Use a dictionary when you need to associate specific pieces of data with unique identifiers, like storing properties of a user or a product.
Which of the following correctly creates a Python dictionary?
Given the dictionary product = {"item": "Book", "price": 15.99}, how would you access the price?
