Python Dictionaries
A dictionary in Python is an unordered, mutable collection that stores key-value pairs.
- Each key must:
- be unique
- be associated with a specific value
- defined using curly braces
{}and specifying key-value pairs separated by colons: - Purpose:
- Key-Value Mapping
- allow you to associate values with descriptive keys, providing a convenient way to represent relationships between data
- Fast Retrieval
- Due to hashing, dictionaries offer fast and efficient retrieval of values based on keys
- Flexibility
- versatile for representing complex data structures, configurations, and mappings
- Key-Value Mapping
- Uses
- ideal when you need to organize data in a way that facilitates efficient and expressive access
- useful in network automation for managing information about devices, configurations, or any data that involves a key-value relationship
# Dictionary representing network devices
network_devices = {
'Router1': '192.168.1.1',
'Switch1': '10.0.0.1',
'Firewall1': '172.16.0.1',
'Server1': '192.168.2.1',
}
# Accessing information about a specific device
router_ip = network_devices['Router1']
# Adding a new device to the dictionary
network_devices['Switch2'] = '10.0.0.2'
# Resulting updated dictionary
# {'Router1': '192.168.1.1', 'Switch1': '10.0.0.1', 'Firewall1': '172.16.0.1', 'Server1': '192.168.2.1', 'Switch2': '10.0.0.2'}Dictionary Data Types
- key-value pairs can be of various data types
- Common data types
- Keys:
- Keys can be of any immutable data type
- e.g., integers, strings, or tuples
- Lists and dictionaries cannot be used as keys
- are mutable
- Keys can be of any immutable data type
- Values:
- Values can be of any data type
- Keys:
Dictionary Constructor
The dictionary constructor dict() is a built-in function that allows you to create a dictionary from various data structures.
- can take no arguments, a dictionary, or an iterable containing key-value pairs
- Role and function:
- creating empty dictionaries
- converting from iterables
- copying dictionaries
# Example: Creating a dictionary using the constructor for network devices
device_list = [('Router1', '192.168.1.1'), ('Switch1', '10.0.0.1'), ('Firewall1', '172.16.0.1')]
# Using the dictionary constructor to convert a list of tuples into a dictionary
network_devices = dict(device_list)
# Resulting dictionary: {'Router1': '192.168.1.1', 'Switch1': '10.0.0.1', 'Firewall1': '172.16.0.1'}Access Dictionary Values
- items in a dictionary can be accessed using their keys in quotes
""in brackets[]
# Define a dictionary
dict1 = {"key1": "value1", "key2": "value2", "key3": "value3"}
# Access an item using its key
value1 = dict1["key1"]- If key does not exist
- returns
KeyError
- returns
- Can use
getmethod instead which returnsNone- e.g.,
value = dict1.get("non_existent_key") - can specify a default value as second parameter
- e.g.,
value = dict1.get("non_existent_key", "default_value")
- e.g.,
- e.g.,
Modifying Dictionary Items
Change Dictionary Item
- change the values in a dictionary by directly assigning a new value to a specific key
# Creating a dictionary
network_devices = {
'Router1': '192.168.1.1',
'Switch1': '10.0.0.1',
'Firewall1': '172.16.0.1',
'Server1': '192.168.2.1',
}
# Changing the value of a specific key
network_devices['Router1'] = '192.168.1.100'- nested dicts:
nested_dict['outer_key']['inner_key'] = 'new_value'
Remove Item From Dictionary
- Can remove an item from dictionary using:
delkeyword- e.g.,
del dictionary['key1']
- e.g.,
pop()method- returns the value of removed item
- e.g.,
value = dictionary.pop('key1')
Update a Dictionary
The update() method is used to update a dictionary with the key/value pairs from another dictionary, or from an iterable of key/value pairs.
- if a key in the second dictionary already exists in the first dictionary, the value for that key in the first dictionary will be updated
- If a key in the second dictionary does not exist in the first dictionary, a new item with that key and value will be added to the first dictionary
# Define two dictionaries
dict1 = {"key1": "value1", "key2": "value2"}
dict2 = {"key2": "new_value2", "key3": "value3"}
# Update dict1 with dict2
dict1.update(dict2)
# New values:
# dict1 = {"key1": "value1", "key2": "new_value2", "key3": "value3"}Adding Dictionary Items
To add an item to a Python dictionary, simply assign a value to a new key in the dictionary.
dictionary = {'key1': 'value1', 'key2': 'value2'}
dictionary['key3'] = 'value3'Clearing a Dictionary
To clear a Python dictionary, the clear() method is used.
dictionary = {'key1': 'value1', 'key2': 'value2'}
dictionary.clear()