4.5 - Working With Dictionaries
Dictionaries are unordered collections of key-value pairs. In Python, dictionaries are defined with curly braces {}
containing keys and values, e.g., {key1: value1, key2: value2}
. Keys act as unique identifiers for values, and values can be of any data type.
Dictionaries are mutable, allowing modification of their contents. The keys in a dictionary must be immutable (like strings, numbers, or tuples) and unique, while the values can be of any data type and can be duplicated.
4.5.1 - Creating Dictionaries
Dictionaries are created by enclosing key-value pairs in curly braces {}
:
# An empty dictionary
empty_dict = {}
# Dictionary with integer keys
int_key_dict = {1: 'apple', 2: 'banana'}
# Dictionary with mixed key types
mixed_dict = {'name': 'John', 1: [2, 4, 3]}
Alternatively, the dict()
constructor can be used:
# Using dict() with keyword arguments
dict_with_keywords = dict(first='apple', second='banana')
# Using dict() with a list of tuples
dict_from_tuples = dict([('first', 'apple'), ('second', 'banana')])
4.5.2 - Accessing Dictionary Elements
Elements in a dictionary can be accessed using their keys:
# Accessing an element
element = int_key_dict[1] # 'apple'
# Accessing using get()
element_with_get = int_key_dict.get(1) # 'apple'
4.5.3 - Modifying Dictionaries
Dictionaries are mutable. You can add new key-value pairs or modify existing ones:
# Adding a new key-value pair
int_key_dict[3] = 'orange'
# Modifying an existing key
int_key_dict[2] = 'blueberry'
4.5.4 - Removing Elements from Dictionaries
Elements can be removed from a dictionary using several methods:
.pop(key)
: Removes the item with the specified key and returns its value..popitem()
: Removes and returns the last key-value pair.del
: Removes an item or the entire dictionary..clear()
: Empties the dictionary.
Example:
removed_value = int_key_dict.pop(3)
int_key_dict.popitem()
del int_key_dict[1]
int_key_dict.clear()
4.5.5 - Iterating Over Dictionaries
You can iterate over the keys, values, or key-value pairs in a dictionary:
# Iterating over keys
for key in int_key_dict:
print(key)
# Iterating over values
for value in int_key_dict.values():
print(value)
# Iterating over key-value pairs
for key, value in int_key_dict.items():
print(key, value)
4.5.6 - Checking if a Key Exists
To check if a key exists in a dictionary, use the in
keyword:
if 2 in int_key_dict:
print("Key 2 exists in the dictionary")
4.5.7 - Dictionary Length
The len()
function returns the number of key-value pairs in the dictionary:
length = len(int_key_dict)
4.5.8 - Nested Dictionaries
Dictionaries can contain other dictionaries, creating nested structures:
nested_dict = {1: {'name': 'John', 'age': 27}, 2: {'name': 'Marie', 'age': 22}}
4.5.9 - Dictionary Comprehensions
Dictionary comprehensions offer a concise way to create dictionaries:
squared_dict = {x: x**2 for x in range(6)}
4.5.10 - Merging Dictionaries
Dictionaries can be merged in several ways:
- Using the
update()
method. - Using the
|
operator (Python 3.9+).
Example:
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
# Using update()
dict1.update(dict2) # dict1 is now {'a': 1, 'b': 3, 'c': 4}
# Using the | operator
merged_dict = dict1 | dict2 # {'a': 1, 'b': 3, 'c': 4}
4.5.11 - Summary Table of Dictionary Operations and Features
Operation/Feature | Description | Example |
---|---|---|
Creating Dictionaries | Define a dictionary with {} or dict() . | d = {1: 'apple', 2: 'banana'} |
Accessing Elements | Access elements by their key. | element = d[1] |
Modifying Dictionaries | Add or modify elements by key. | d[3] = 'orange' |
Removing Elements | Remove elements using various methods. | removed = d.pop(3) |
Iterating Over Dictionaries | Iterate over keys, values, or pairs. | for k, v in d.items(): print(k, v) |
Checking Key Existence | Check if a key exists. | if 2 in d: ... |
Dictionary Length | Get the number of key-value pairs. | len(d) |
Nested Dictionaries | Use dictionaries within dictionaries. | nested = {1: {'name': 'John'}} |
Dictionary Comprehensions | Concise way to create dictionaries. | squared = {x: x**2 for x in range(6)} |
Merging Dictionaries | Merge dictionaries using methods or ` | `. |