Introduction
In this lesson on dictionaries, we will explore the versatile and powerful data structure of key-value pairs in Python. Dictionaries act as a primary method for storing and retrieving data efficiently using unique keys. This lesson will guide you through creating dictionaries using multiple constructors, manipulating dictionary items safely, leveraging different methods for data retrieval and updates, and implementing dictionaries in practical scenarios such as counting elements and mapping configurations.
Creating Dictionaries
Using Dictionary Literals
The most straightforward way to create a dictionary is using curly braces {} to define key-value pairs.
fruits = {'apple': 2.5, 'banana': 1.2, 'cherry': 3.0}
Using the dict() Constructor
An alternative is using the dict() constructor, which creates dictionaries from keyword arguments or iterable pairs.
animal_ages = dict(cat=5, dog=7, turtle=40)
From Sequences of Pairs
You can also form dictionaries from tuples or lists of key-value pairs.
pairs = [('name', 'Alice'), ('age', 25), ('city', 'New York')]
person = dict(pairs)
Accessing and Manipulating Dictionaries
Accessing Values Safely
Retrieve values for a specified key using the square bracket [] notation. Use get() when uncertain if a key exists, as it won't cause errors.
print(person['name']) # Direct access
age = person.get('age') # Safe access
Inserting and Updating Elements
Insert new items by assigning a value to a new key, or update the existing key.
person['occupation'] = 'Engineer' # Inserting
person['age'] = 30 # Updating
Deleting Key-Value Pairs
Remove items with the del statement or pop() method. Use pop() to both remove and return the value.
del person['city'] # Using del
occupation = person.pop('occupation') # Using pop()
# Output
# Alice is now 30 years old, and removed 'Engineer'
Iterating Over Dictionaries
Iterating Keys, Values, and Items
Python provides efficient ways to iterate through keys, values, or items simultaneously.
for key in person.keys():
print(key)
for value in person.values():
print(value)
for key, value in person.items():
print(f"{key}: {value}")
Utilizing Dictionary Methods
Methods Overview
keys(): Returns an iterable view of keys.values(): Returns an iterable view of values.items(): Returns an iterable view of key-value pairs.update(): Merges another dictionary into the current dictionary.clear(): Eliminates all items in the dictionary.
Example of update():
new_details = {'hobby': 'painting'}
person.update(new_details)
# Output
# {'name': 'Alice', 'age': 30, 'hobby': 'painting'}
Practical Applications
Using Dictionaries for Counting Elements
Dictionaries can efficiently count occurrences. Here’s a simple counting example:
items = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
count = {}
for item in items:
count[item] = count.get(item, 0) + 1
Lookups and Mapping
Dictionaries allow fast lookups, ideal for mapping configurations or settings.
default_colors = {'header': 'blue', 'text': 'black', 'background': 'white'}
text_color = default_colors.get('text', 'default color')
Summary / Key Takeaways
In this lesson on Dictionaries: Key-Value Storage, you have learned:
- Create dictionaries using literals, the
dict()constructor, and from sequences of pairs. - Safely access and modify dictionary items with methods like
get()andpop(). - Efficient iteration over keys, values, and items using dictionary view methods.
- Enhance dictionary usage with built-in methods like
keys(),values(),items(),update(), andclear(). - Apply dictionaries in practical scenarios for counting occurrences, fast lookups, and mapping configurations.
