Dictionaries
Imagine you have a list of contacts, and you want to store each person’s name along with their phone number. Keeping two separate lists for names and phone numbers could get messy. Instead, wouldn’t it be easier to pair each name directly with its corresponding phone number? That’s where dictionaries in Python shine!
What are Dictionaries?
A dictionary is a collection of key-value pairs, where:
- The key is like a label (e.g., a name).
- The value is the data associated with that key (e.g., a phone number).
Dictionaries make it easy to organize and retrieve information by key.
Creating a Dictionary
Dictionaries in Python are created using curly braces { }
key: value
contacts = {
"Alice": "555-1234",
"Bob": "555-5678",
"Charlie": "555-8765"
}
In this example:
,"Alice" , and"Bob"
are keys."Charlie"
,"555-1234" , and"555-5678"
are their corresponding values."555-8765"
Accessing values
To retrieve a value, use the key inside square brackets [ ]
print(contacts["Alice"]) # Output: "555-1234"
Here, we use "Alice"
Adding or updating items
Dictionaries are mutable, meaning you can add or update items after creating them.
Adding an item
contacts["Dave"] = "555-4321"
print(contacts)
# Output: {"Alice": "555-1234", "Bob": "555-5678", "Charlie": "555-8765", "Dave": "555-4321"}
Updating an item
contacts["Alice"] = "555-0000"
print(contacts["Alice"]) # Output: "555-0000"
Removing items
You can remove key-value pairs using the del
.pop()
Using del
del
del contacts["Charlie"]
print(contacts)
# Output: {"Alice": "555-1234", "Bob": "555-5678"}
Using .pop()
.pop()
The .pop()
removed_number = contacts.pop("Bob")
print(removed_number) # Output: "555-5678"
print(contacts) # Output: {"Alice": "555-1234"}
Common Dictionary operations
Checking for a key
You can check if a key exists in the dictionary using the in
print("Alice" in contacts) # Output: True
print("Eve" in contacts) # Output: False
Getting all keys and values
-
Use
to get a list of all keys:.keys()
print(contacts.keys()) # Output: dict_keys(["Alice", "Dave"])
-
Use
to get all values:.values()
print(contacts.values()) # Output: dict_values(["555-1234", "555-4321"])
Iterating through a Dictionary
To loop through key-value pairs, .items()
for name, number in contacts.items():
print(name, ":", number)
# Output:
# Alice : 555-1234
# Dave : 555-4321
Why use Dictionaries?
Dictionaries are ideal when you need to:
- Organize data with unique identifiers (e.g., names, IDs, or labels).
- Quickly look up data by key.
- Group related information in a structured format.
Examples:
- Contacts list (name → phone number).
- Settings in a program (e.g.,
{"volume": 70, "brightness": 50}
). - Word counts in a text.
Practical examples
1. Storing student grades
grades = {
"John": 88,
"Sally": 92,
"Tom": 75
}
print(grades["Sally"]) # Output: 92
2. Product prices
prices = {
"apple": 0.99,
"banana": 0.59,
"orange": 0.79
}
prices["apple"] = 1.09 # Update the price of an apple
print(prices["apple"]) # Output: 1.09
3. Counting word frequencies
text = "hello world hello everyone"
word_counts = {}
for word in text.split():
word_counts[word] = word_counts.get(word, 0) + 1
print(word_counts) # Output: {"hello": 2, "world": 1, "everyone": 1}
Conclusion
Dictionaries in Python are a powerful and flexible way to store data as key-value pairs. They allow for quick lookups, easy modifications, and efficient data organization. Whether managing contacts, analyzing text, or tracking inventory, dictionaries are a go-to tool for many programming tasks.