13.Dictionaries Deep Dive
Dictionaries in Python are powerful, mutable collections that store data as key-value pairs. They are widely used for mapping relationships, fast lookups, and structured data representation. Unlike sequences, dictionaries are unordered (prior to Python 3.7) and keys must be unique and hashable.
Creating Dictionaries
You can create dictionaries using curly braces {} or the dict() constructor. Keys and values can be of various types.
Examples
my_dict = {‘name’: ‘Alice’, ‘age’: 25}
empty_dict = {}
dict_from_pairs = dict([(‘x’, 1), (‘y’, 2)])
Accessing and Modifying Elements
Access values using keys. Modify or add new key-value pairs directly.
Example:
print(my_dict[‘name’]) # Alice
my_dict[‘age’] = 26
my_dict[‘city’] = ‘New York’
Common Dictionary Methods
Method | Description |
keys() | Returns a view of all keys |
values() | Returns a view of all values |
items() | Returns a view of key-value pairs |
get(key[, default]) | Returns value for key or default |
update([other]) | Updates dictionary with key-value pairs from other |
pop(key[, default]) | Removes and returns value for key |
popitem() | Removes and returns last inserted key-value pair |
clear() | Removes all items |
copy() | Returns a shallow copy of the dictionary |
Dictionary Operations
Dictionaries support operations like merging, updating, and iterating over keys, values, and items.
Example:
dict1 = {‘a’: 1, ‘b’: 2}
dict2 = {‘b’: 3, ‘c’: 4}
dict1.update(dict2) # {‘a’: 1, ‘b’: 3, ‘c’: 4}
for key, value in dict1.items():
print(key, value)
Advanced Features
Dictionary Comprehensions:
squares = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Nested Dictionaries:
nested = {
‘person1’: {‘name’: ‘Alice’, ‘age’: 25},
‘person2’: {‘name’: ‘Bob’, ‘age’: 30}
}
Best Practices
– Use immutable types (like strings, numbers, tuples) as keys.
– Avoid modifying dictionary size during iteration.
– Use get() or setdefault() to handle missing keys safely.
– Consider defaultdict or Counter from collections for specialized use cases.
– For large datasets, be mindful of memory usage and consider alternatives like pandas or databases.