What does a real dictionary you find in a library contain? A traditional dictionary has a definition for each term. In other words, there is a definition associated with each term.
A Python dictionary data type (and some particular data structures such as the map) also stores associations, but the types of data for 'what' is associated with 'what' can be any valid object type. The Python dictionary associates a “value” with each “key,” meaning that the key is used to 'look up' the associated value.
In Python terms, a dictionary contains a group of “items,” where each item contains a key and the associated value. Some people refer to this kind of item as a “mapping.”
Characteristics of Python Dictionaries
- Unordered Collections:
-
- Dictionaries are unordered collections of key-value pairs. Unlike lists or tuples, dictionaries do not maintain any order for the elements.
- In Python 3.7 and later, dictionaries maintain the insertion order, although this behavior should not be relied upon for algorithmic complexity guarantees.
- Key-Value Pairs:
- Each item in a dictionary is a pair consisting of a key and a value. Keys must be unique and immutable (e.g., strings, numbers, or tuples), while values can be of any data type and can be duplicated.
- Mutable:
- Dictionaries are mutable, meaning you can change, add, or remove key-value pairs after the dictionary has been created.
- Fast Lookups:
- Dictionaries are implemented using hash tables, which allows for fast lookup, insertion, and deletion operations. The average time complexity for these operations is O(1).
- Dynamic:
- Dictionaries can grow and shrink as needed, just like lists.
- Built-in Methods:
- Dictionaries come with several built-in methods:
- keys(): Returns a view object that displays a list of all the keys.
- values(): Returns a view object that displays a list of all the values.
- items(): Returns a view object that displays a list of tuples, each containing a key-value pair.
- get(key[, default]): Returns the value for the specified key if the key is in the dictionary; otherwise, returns the default value.
- update([other]): Updates the dictionary with elements from another dictionary or from an iterable of key-value pairs.
- pop(key[, default]): Removes the specified key and returns the corresponding value. If the key is not found, returns the default value.
- popitem(): Removes and returns an arbitrary key-value pair as a tuple.
- Dictionaries come with several built-in methods:
Creating a Dictionary
A dictionary can be created in Python by:
- Calling the dict constructor function:
d = dict([["roses", "red"], ["violets", "blue"]]) |
- Declaring a dictionary using an initializer with the proper syntax:
d = {"alice": "bob", "spam": "eggs"} |
Although there are a few variations of the constructor method, you must pass in the data for the keys and values separately. In the constructor example above, the data is passed as a list of lists, where each inner list contains a key and its associated value.
Accessing Dictionary Items
Assuming your dictionary is stored in a variable and contains the associations (items) already, you can 'look up' the value for a key by indexing the dictionary.
d = {"alice": "bob", "spam": "eggs"} d["alice"] # Output: 'bob' |
Adding Items to a Dictionary
Adding an item to an existing dictionary can be done by using a new index and setting the new value.
d["alice"] = "bob" |
Retrieving Items from a Dictionary
You can use the get method to retrieve the value associated with a key.
d.get("alice") # Output: 'bob' |
Removing Items from a Dictionary
Removing an item from the dictionary can be done by calling the pop method. This will remove the item and any association between “bob” and the value.
d.pop("bob") |
Another way to remove an item is by using the del keyword. Using the del keyword is another more universal way to remove an object or part of one, and of course it applies to a dictionary:
del d["alice"] |
This removes the association between “alice” and its value.
Other Dictionary Operations
Though the most common tasks with a dictionary are most likely adding or removing items and retrieving the value for a key, a good Python programmer will exercise all of its capabilities.
Other dictionary class functions like keys and values will produce the current contents of the keys or the values in the dictionary.
- Keys and Values: You can retrieve the keys and values of a dictionary using the keys and values methods.
d = {"alice": "bob", "spam": "eggs"} d.keys() # Output: dict_keys(['alice', 'spam']) list(d.keys()) # Output: ['alice', 'spam'] d.values() # Output: dict_values(['alice', 'spam']) list(d.values()) # Output: ['bob', 'eggs'] |
Ultimately, the primary use of a dictionary is for storing associations and retrieving them. Do you think a Python dictionary would be useful for tracking the number of occurrences of each word in a document? Take a moment to consider your answer before continuing.
Since a particular value, an integer count, would be associated with each word, which is a string, the dictionary is a highly effective data type and data structure for the word count problem.
In reality, there are endless applications for the storage and processing of associations, as there are numerous interpretations of data that can exhibit associations.
Example Usage
# Creating a dictionary student_scores = { "Alice": 85, "Bob": 90, "Charlie": 78 } # Accessing values by key print(student_scores["Alice"]) # Output: 85 # Adding a new key-value pair student_scores["David"] = 92 # Updating an existing key-value pair student_scores["Alice"] = 88 # Removing a key-value pair del student_scores["Charlie"] # Iterating over keys for student in student_scores: print(student, student_scores[student]) # Using built-in methods keys = student_scores.keys() values = student_scores.values() items = student_scores.items() print(keys) # Output: dict_keys(['Alice', 'Bob', 'David']) print(values) # Output: dict_values([88, 90, 92]) print(items) # Output: dict_items([('Alice', 88), ('Bob', 90), ('David', 92)]) |
Example 1: Word Count
A Python dictionary can be useful in tracking the number of occurrences of each word in a document. Since a particular value (an integer count) would be associated with each word (a string), the dictionary is a highly effective data type and data structure for this problem.