unit 10 review
Dictionaries in Python are powerful data structures that store key-value pairs. They offer efficient data retrieval and organization, making them essential for representing real-world objects and managing complex data relationships.
This unit covers dictionary creation, accessing values, and common operations. It also explores nested dictionaries, comprehensions, and advanced techniques like sorting and using specialized dictionary classes from the collections module.
What Are Dictionaries?
- Dictionaries are a built-in data type in Python used to store and organize data in key-value pairs
- Consist of a collection of keys, each associated with a specific value
- Keys must be unique and immutable objects (strings, numbers, or tuples), while values can be of any data type
- Provide efficient lookup and retrieval of values based on their associated keys
- Unordered data structure, meaning the elements are not stored in a specific order
- Enclosed in curly braces
{} with each key-value pair separated by a comma
- Useful for representing real-world objects or entities with multiple attributes (person with name, age, and address)
Creating and Accessing Dictionaries
- Dictionaries can be created using curly braces
{} or the dict() constructor
- Key-value pairs are defined using a colon
: to separate the key from its corresponding value
- Values are accessed by specifying the key within square brackets
[]
- Attempting to access a key that doesn't exist raises a
KeyError
- The
get() method can be used to retrieve a value by its key, returning a default value if the key is not found
- Syntax:
dictionary.get(key, default_value)
- Individual key-value pairs can be added or modified using the square bracket notation
dictionary[key] = value
- Dictionaries are mutable, allowing for the addition, modification, and deletion of key-value pairs
Dictionary Methods and Operations
len(dictionary) returns the number of key-value pairs in the dictionary
dictionary.keys() returns a view object containing all the keys in the dictionary
dictionary.values() returns a view object containing all the values in the dictionary
dictionary.items() returns a view object containing all the key-value pairs as tuples
dictionary.update(other_dictionary) merges the key-value pairs from other_dictionary into the original dictionary
dictionary.pop(key) removes and returns the value associated with the specified key, raising a KeyError if the key is not found
dictionary.clear() removes all key-value pairs from the dictionary, leaving it empty
del dictionary[key] removes the key-value pair with the specified key from the dictionary
key in dictionary checks if a key exists in the dictionary, returning True or False
Nested Dictionaries
- Dictionaries can contain other dictionaries as values, creating nested or hierarchical structures
- Nested dictionaries are useful for representing complex data with multiple levels of organization (employee records with personal info and job details)
- Accessing values in nested dictionaries involves chaining square brackets or using the
get() method for each level
- Example:
employee_data[employee_id]['personal_info']['address']
- Modifying or adding values in nested dictionaries follows a similar approach, using square brackets to navigate through the levels
Dictionary Comprehensions
- Dictionary comprehensions provide a concise way to create dictionaries based on existing iterables or conditions
- Similar to list comprehensions, dictionary comprehensions use curly braces
{} and a key-value pair definition
- Syntax:
{key_expression: value_expression for item in iterable if condition}
- Key and value expressions define how the keys and values are derived from the iterable
- The
if condition is optional and filters the items from the iterable
- Dictionary comprehensions are useful for transforming data or creating dictionaries with computed keys and values
Common Use Cases for Dictionaries
- Storing and accessing data based on unique identifiers or keys (student records, product catalogs)
- Counting the frequency of items in a list or string
- Example:
word_count = {word: text.count(word) for word in set(text.split())}
- Grouping or categorizing data based on specific criteria (grouping employees by department)
- Implementing lookup tables or mappings between different sets of values
- Caching expensive computations or frequently accessed data for faster retrieval
- Representing graph data structures, where vertices are keys and edges are stored as values (adjacency list representation)
Dictionaries vs. Other Data Structures
- Dictionaries provide fast lookup and retrieval of values based on keys, with an average time complexity of O(1)
- Lists and tuples are ordered sequences accessed by integer indices, while dictionaries are unordered and accessed by keys
- Sets are unordered collections of unique elements, similar to the keys in a dictionary, but without associated values
- Arrays in Python (NumPy) are optimized for numerical computations and have fixed sizes, while dictionaries are more flexible and can store heterogeneous data types
- Dictionaries are suitable for scenarios requiring fast key-based access, while lists and tuples are used for ordered sequences, and sets for unique elements
Advanced Dictionary Techniques
- Dictionaries can be sorted by keys or values using the
sorted() function and a key function
- Example:
sorted(dictionary.items(), key=lambda x: x[1]) sorts the dictionary by values
- The
defaultdict from the collections module automatically initializes missing keys with a default value or factory function
- Useful for counting or grouping elements without explicitly checking for key existence
- The
Counter class from the collections module is a subclass of dict used for counting hashable objects
- Provides methods like
most_common() to retrieve the most common elements and their counts
- Dictionaries can be serialized and deserialized using the
json module for data exchange or storage
json.dumps(dictionary) converts a dictionary to a JSON string
json.loads(json_string) converts a JSON string back to a dictionary