Dictionaries
Dictionaries
We've already discusses lists and tuples, which are ordered collections of items where each item is identified by its index. In contrast, dictionaries are unordered collections of items where each item is identified by a unique key.
Concept: Dictionary
A dictionary is a collection of key-value pairs, where each key is unique and maps to a specific value. Dictionaries are unordered, meaning that the items do not have a defined order, and they are mutable, allowing you to add, remove, or change items after the dictionary has been created.
Keys must be of an immutable data type, such as strings, numbers (float and int), or tuples of those types. The values can be of any data type, including dictionaries, lists, functions[1], or other complex data structures.
Dictionaries are created using curly braces {} and separating the key-value pairs with commas. Each key is separated from its value by a colon :.
config = {
"hostname": "srv01.example.com",
"ip_address": "192.168.1.10",
"services": ["ssh", "http", "ssh"]
}As you've seen above, dictionaries are useful for storing and organizing data where the key is important. Configuration files in JSON or YAML format are often represented as dictionaries in Python, where the keys represent the configuration options and the values represent their corresponding settings.
Once we've covered IO operations in a later chapter, you'll be able to dynamically read configurations files and edit them using a Python script, or even generate new configuration files based on user input or other data sources.
Adding items to a dictionary
Adding items to a dictionary is straightforward. Dictionaries are a mutable collection type like lists, meaning that you can add, remove, or change items after the dictionary has been created using the key as an indexer expression.
config = {
"hostname": "srv01.example.com",
"ip_address": "192.168.1.10",
"services": ["ssh", "http", "ssh"]
}
# Reading an item works the same as for a list; use the indexer notation and
# a key as the indexer-value.
hostname = config["hostname"]
# Adding and updating items also works the same way.
config["users"] = ["Alice", "Bob", "Charlie", "David", "Charlie"]
print(config["users"]) # Output: ["Alice", "Bob", "Charlie", "David", "Charlie"]Working with dictionaries
Concept: Dictionary methods
A dictionary has several methods that can be used to manipulate its contents. Some of the most commonly used methods are:
get(): Returns the value for a specified key. If the key does not exist, it returns a default value (orNoneif no default is provided).user = {"firstName": "Alice", "lastName": "Healy", "age": 30, "username": "alice_h"} print(user.get("username")) # Output: alice_h print(user.get("gender", "Not specified")) # Output: Not specifiedkeys(): Returns a view object that displays a list of all the keys in the dictionary.user = {"firstName": "Alice", "lastName": "Healy", "age": 30, "username": "alice_h"} print(user.keys()) # Output: dict_keys(['firstName', 'lastName', 'age', 'username'])values(): Returns a view object that displays a list of all the values in the dictionary.user = {"firstName": "Alice", "lastName": "Healy", "age": 30, "username": "alice_h"} print(user.values()) # Output: dict_values(['Alice', 'Healy', 30, 'alice_h'])items(): Returns a view object that displays a list of all the key-value pairs in the dictionary. Those pairs are represented as 2-tuples or pairs.user = {"firstName": "Alice", "lastName": "Healy", "age": 30, "username": "alice_h"} print(user.items()) # Output: dict_items([('firstName', 'Alice'), ('lastName', 'Healy'), ('age', 30), ('username', 'alice_h')])pop(): Removes the specified key and returns the corresponding value. If the key does not exist, it raises aKeyError.user = {"firstName": "Alice", "lastName": "Healy", "age": 30, "username": "alice_h"} removed_value = user.pop("age") print(removed_value) # Output: 30 print(user) # Output: {'firstName': 'Alice', 'lastName': 'Healy', 'username': 'alice_h'}update(): Updates the dictionary with key-value pairs from another dictionary or an iterable of key-value pairs. If a key already exists, its value will be updated.user = {"firstName": "Alice", "lastName": "Healy", "age": 30, "username": "alice_h"} user.update({"age": 31, "gender": "female"}) print(user) # Output: {'firstName': 'Alice', 'lastName': 'Healy', 'age': 31, 'username': 'alice_h', 'gender': 'female'}clear(): Removes all items from the dictionary.user = {"firstName": "Alice", "lastName": "Healy", "age": 30, "username": "alice_h"} user.clear() print(user) # Output: {}
Functions wil be covered in the next chapter. ↩︎