A dictionary in Python is an unordered, mutable, and indexed collection of key-value pairs. It is used to store data values where each key is unique and associated with a specific value. Dictionaries are implemented as hash tables, making operations like lookup, insertion, and deletion very efficient.
Key Features of Dictionaries
- Key-Value Pairs: Each element in a dictionary is a key-value pair: {key: value}.
- Keys Must Be Unique: Duplicate keys are not allowed; the latest value overwrites the previous one.
- Keys Must Be Immutable: Keys must be hashable types like strings, numbers, or tuples (containing only immutable elements).
- Values Can Be Any Type: Values can be of any data type and may be duplicated.
Creating a Dictionary
- Using Curly Braces {}:
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
- Using the dict() Constructor:
my_dict = dict(name='Alice', age=25, city='New York')
- Empty Dictionary:
empty_dict = {}
Accessing Dictionary Elements
Accessing Values
- Using Keys:
print(my_dict['name']) # Output: Alice
If the key doesn’t exist, it raises a KeyError.
- Using get():
print(my_dict.get('age')) # Output: 25 print(my_dict.get('country', 'USA')) # Output: USA (default value)
Adding and Updating Elements
- Adding a New Key-Value Pair:
my_dict['country'] = 'USA'
- Updating a Value:
my_dict['age'] = 30
Removing Elements
- Using pop(): Removes a key and returns its value. Raises KeyError if the key is not found.
age = my_dict.pop('age') print(age) # Output: 25
- Using popitem(): Removes and returns the last inserted key-value pair (for Python 3.7+).
key, value = my_dict.popitem() print(key, value)
- Using del: Deletes a key-value pair or the entire dictionary.
del my_dict['name'] del my_dict # Deletes the entire dictionary
- Using clear(): Removes all elements.
my_dict.clear()
Dictionary Operations
- Check if a Key Exists
if 'name' in my_dict: print("Key exists!")
- Iterating Through a Dictionary
- Keys:
for key in my_dict: print(key)
- Values:
for value in my_dict.values(): print(value)
- Key-Value Pairs:
for key, value in my_dict.items(): print(f"{key}: {value}")
- Keys:
Dictionary Methods
Method | Description |
get(key, default) |
Returns the value for a key, or a default value if the key does not exist.
|
keys() | Returns a view object of all keys. |
values() | Returns a view object of all values. |
items() |
Returns a view object of all key-value pairs as tuples.
|
update(other_dict) |
Updates the dictionary with key-value pairs from another dictionary or iterable.
|
pop(key) | Removes the key and returns its value. |
popitem() |
Removes and returns the last inserted key-value pair.
|
clear() | Removes all elements from the dictionary. |
copy() | Returns a shallow copy of the dictionary. |
Examples of Usage
- Merging Dictionaries
dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3, 'c': 4} dict1.update(dict2) # {'a': 1, 'b': 3, 'c': 4}
- Dictionary Comprehension
squares = {x: x**2 for x in range(5)} print(squares) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
- Counting Elements
from collections import Counter words = ['apple', 'banana', 'apple'] count = Counter(words) print(count) # Output: {'apple': 2, 'banana': 1}
Advantages of Dictionaries
- Fast Lookups: Optimized for retrieving values by keys.
- Flexible Values: Can store any data type as values.
- Dynamic: Can grow or shrink dynamically.
- Readable: Key-value format makes the data easy to interpret.
Disadvantages of Dictionaries
- Unordered (Prior to Python 3.7): Does not maintain the insertion order.
- Memory Overhead: Consumes more memory than lists or tuples.
- Immutable Keys Only: Cannot use mutable types like lists as keys.
Dictionaries are an essential data structure for scenarios requiring fast lookups and mappings between keys and values.