Python Dictionaries (Dictionary)
Dictionaries are a very flexible and powerful built-in data type in Python. They store data in the form of key-value pairs, providing an efficient way to look up, add, and remove entries.
Dictionary Characteristics
- Key-Value Pairs: Each element consists of a unique "key" and a corresponding "value".
- Unordered (Historical): In versions before Python 3.7, dictionaries were unordered. Starting with Python 3.7, dictionaries maintain the insertion order of elements.
- Mutable: Dictionaries are mutable; you can add, modify, or delete key-value pairs at any time.
- Unique Keys: Keys in a dictionary must be unique and must be of immutable type (such as strings, numbers, or tuples). Values can be of any type and can be repeated.
Creating Dictionaries
Dictionaries are defined using curly braces {}, containing a series of key: value pairs.
Accessing Dictionary Elements
You can access corresponding values through keys.
Using Square Brackets []
Using .get() Method
The .get() method is safer; if the key doesn't exist, it returns None (or a default value you specify) instead of raising an error.
Modifying and Adding Elements
You can add new key-value pairs or modify existing values through keys.
Deleting Elements
del dict[key]: Deletes the specified key-value pair.dict.pop(key): Deletes and returns the value of the specified key.dict.popitem(): Deletes and returns the last inserted key-value pair (in Python 3.7+).dict.clear(): Empties the dictionary.
Iterating Over Dictionaries
There are several ways to iterate over all elements in a dictionary.
.keys(), .values(), and .items() return special "view objects" that provide dynamic views of dictionary entries, meaning if the dictionary changes, the views will reflect those changes accordingly.