Python dictionaries are unordered collections of key-value pairs. They are highly optimized for retrieving values when the key is known. Dictionaries are mutable, allowing you to change, add, or remove key-value pairs.
A dictionary in Python is created by placing a comma-separated sequence of key-value pairs within curly braces {}
.
Example:
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
Keys must be unique and hashable (e.g., strings, numbers, tuples). Values can be of any data type and can be duplicated.
collections.OrderedDict
.Accessing Values by Key: Retrieve a value by its key.
my_dict = {'name': 'Alice', 'age': 25}
name = my_dict['name'] # 'Alice'
get(key, default=None)
: Retrieve a value by key, with an optional default if the key is not found.
age = my_dict.get('age', 0) # 25
city = my_dict.get('city', 'Unknown') # 'Unknown'
my_dict['city'] = 'New York' # Adds a new key-value pair
my_dict['age'] = 26 # Updates the existing value
del
statement: Remove a key-value pair using the del
statement.
del my_dict['age']
pop(key, default=None)
: Remove a key-value pair by key and return its value. If the key is not found, return the default value.
age = my_dict.pop('age', None) # 25
popitem()
: Remove and return the last inserted key-value pair (as of Python 3.7+).
last_item = my_dict.popitem() # ('city', 'New York')
clear()
: Remove all key-value pairs from the dictionary.
my_dict.clear() # {}
in
operator: Check if a key exists in the dictionary.
exists = 'name' in my_dict # True
Iterating Over Keys:
for key in my_dict:
print(key)
Iterating Over Values:
for value in my_dict.values():
print(value)
Iterating Over Key-Value Pairs:
for key, value in my_dict.items():
print(f"{key}: {value}")
keys()
: Return a view object containing the dictionary's keys.
keys = my_dict.keys() # dict_keys(['name', 'age'])
values()
: Return a view object containing the dictionary's values.
values = my_dict.values() # dict_values(['Alice', 25])
items()
: Return a view object containing the dictionary's key-value pairs.
items = my_dict.items() # dict_items([('name', 'Alice'), ('age', 25)])
update(other_dict)
: Update the dictionary with key-value pairs from another dictionary.
my_dict.update({'city': 'Boston', 'age': 30})
setdefault(key, default=None)
: If the key is in the dictionary, return its value. If not, insert the key with a specified default value.
my_dict.setdefault('country', 'USA') # 'USA'
Mutability of Dictionary Keys: Keys must be immutable, so trying to use a list or another dictionary as a key will raise a TypeError
.
my_dict = {}
my_dict[[1, 2, 3]] = "Invalid" # Raises TypeError
Unexpected Behavior with fromkeys()
: The fromkeys()
method creates a dictionary with specified keys and a single value for all keys. If the value is mutable, changing it for one key will change it for all.
keys = ('a', 'b', 'c')
my_dict = dict.fromkeys(keys, [])
my_dict['a'].append(1)
print(my_dict) # {'a': [1], 'b': [1], 'c': [1]}
Overwriting Keys: Adding a key that already exists will overwrite the existing value without warning.
my_dict['age'] = 25
my_dict['age'] = 30 # Overwrites the previous value
Lists of Tuples: For simple key-value pairs where fast lookup is not required, a list of tuples may suffice.
my_list = [('name', 'Alice'), ('age', 25)]
collections.OrderedDict
: If you need to maintain the order of keys, consider using OrderedDict
from the collections
module.
from collections import OrderedDict
ordered_dict = OrderedDict()
ordered_dict['name'] = 'Alice'
ordered_dict['age'] = 25
collections.defaultdict
: If you need a dictionary that provides a default value for missing keys, use defaultdict
.
from collections import defaultdict
dd = defaultdict(int)
dd['a'] += 1 # {'a': 1}
collections.Counter
: For counting hashable items, use Counter
, a subclass of dict
.
from collections import Counter
count = Counter(['a', 'b', 'a', 'c', 'b', 'a'])
# Counter({'a': 3, 'b': 2, 'c': 1})
This comprehensive guide should help you understand Python dictionaries, their features, and best practices for using them effectively in your programs.