A dictionary in Python is a collection of key-value pairs. It is one of Python’s built-in data structures and is used to store data values like a map. Each key in a dictionary must be unique, immutable, and is associated with a value.
Characteristics of a Dictionary
- Unordered: The items are stored in an unordered manner (as of Python 3.7, dictionaries maintain insertion order).
- Mutable: You can add, modify, or remove items.
- Keys are Unique: No duplicate keys are allowed.
- Keys Must Be Immutable: Keys can be strings, numbers, or tuples (not lists or other dictionaries).
Creating a Dictionary
1. Using Curly Braces
2. Using the dict()
Constructor
Accessing Dictionary Items
- Using Keys
- Using the
get()
Method
Adding and Modifying Items
Removing Items
- Using
pop()
- Using
del
- Using
clear()
Iterating Through a Dictionary
- Keys Only
- Values Only
- Keys and Values
Checking for Keys
Dictionary Methods
Method | Description |
---|---|
get(key, default) |
Returns the value for the specified key. |
keys() |
Returns a view object of all the keys. |
values() |
Returns a view object of all the values. |
items() |
Returns a view object of all the key-value pairs. |
pop(key) |
Removes the specified key and returns its value. |
popitem() |
Removes and returns the last inserted key-value pair (from Python 3.7 onward). |
clear() |
Removes all items from the dictionary. |
update(other_dict) |
Updates the dictionary with items from another dictionary or iterable. |
Examples of Real-World Usage
- Storing User Data
- Counting Occurrences
- Representing JSON Data
Dictionaries are a versatile and essential tool in Python, enabling efficient storage and manipulation of data through key-value pairs.