Python Dictionaries
Python Dictionaries
A dictionary in Python is an unordered, mutable collection of key-value pairs. Each key in a dictionary is associated with a value, and you can retrieve, update, or delete a value by referencing its key. Keys in a dictionary must be unique and immutable (e.g., strings, numbers, tuples), while the values can be of any type.
Key Features of Dictionaries:
- Unordered: Unlike lists and tuples, dictionaries do not maintain any order for their elements.
- Mutable: You can modify the dictionary by adding, updating, or deleting key-value pairs.
- Key-Value Pairs: Each element in the dictionary is stored as a key-value pair.
- Keys Must Be Unique: No two keys in a dictionary can be the same.
- Fast Lookup: Dictionaries offer fast lookups by key.
Dictionary Syntax:
Dictionaries are defined using curly braces {}
, with key-value pairs separated by a colon :
.
Example: Creating a Dictionary
Accessing Dictionary Values:
You can access a value by referencing its corresponding key.
If you try to access a key that doesn’t exist, Python will raise a KeyError
. To avoid this, you can use the .get()
method, which returns None
(or a default value) if the key is not found.
Adding and Updating Elements:
You can add new key-value pairs or update existing ones by assigning values to a key.
Removing Elements:
You can remove elements from a dictionary using several methods:
pop(key)
: Removes the key-value pair for the specified key and returns its value.popitem()
: Removes and returns the last inserted key-value pair (only in Python 3.7+).del
: Removes the key-value pair by key.clear()
: Removes all key-value pairs from the dictionary.
Dictionary Methods:
.keys()
: Returns a list-like view of all the keys in the dictionary..values()
: Returns a list-like view of all the values in the dictionary..items()
: Returns a list-like view of all the key-value pairs in the dictionary.
Looping Through a Dictionary:
You can iterate over the keys, values, or key-value pairs in a dictionary using loops.
Checking for Keys:
You can check whether a key exists in the dictionary using the in
keyword.
Dictionary Comprehension:
You can create dictionaries using dictionary comprehensions, which are concise ways to build a dictionary.
Nesting Dictionaries:
Dictionaries can contain other dictionaries, creating a nested structure.
Example: Dictionary as a Phone Book
Summary:
- A dictionary is a collection of key-value pairs.
- Keys must be unique and immutable, but values can be of any type.
- Dictionaries are useful when you need to associate and retrieve values by key, such as storing a phone book, mapping IDs to values, or building data structures like trees or graphs.