Python
|
Dictionaries
A dictionary is a mutable collection of ordered key-value pairs.
Keys must be unique (no duplicate keys) and immutable (strings, numbers, tuples)
The values can be of any type, including mixed types within the same dictionary: strings, numbers, dictionaries, lists, objects, ...
Creating basic dictionaries:
Use braces ({}) to create a dictionary.
Use commas to separate items in the dictionary.
Empty dictionary:
A dictionary with one key-value pair:
A dictionary with multiple key-value pairs:
Mixed data types:
List/Set/Dictionary of dictionaries:
Create dictionaries using dict() with keyword arguments:
Create dictionaries using dict() with list of tuples:
Create dictionaries using dictionary comprehension:
Tuples as dictionary keys:
This is possible because tuples are immutable.
Accessing keys in a dictionary:
Accessing a key that doesn't exist throws an error:
Using the get function:
It returns default/custom value if the key doesn't exist.
Adding new key-value pairs:
Modifying values in a dictionary:
Using update() method:
Removing key-value pairs:
Removing a specific key and returning its value:
Removing a specific key and returning a tuple with key/value:
Clear dictionary (remove all items):
Looping through all key-value pairs:
Output:
Looping through all keys in a dictionary:
Output:
Looping through all values in a dictionary:
Output:
Looping through all sorted keys:
Output:
Looping through all sorted keys (reversed order):
Output:
Looping through all sorted values (reversed order):
Output:
Looping through all the unique values in a dictionary:
Output:
Dictionary comprehensions:
Merging Dictionaries:
Conflicting keys will be resolved by taking the values from the last dictionary in the list of dictionaries to merge:
Copying dictionaries: