About Python Dictionaries
tags: #python/documentation/dictionaries
What are Python Dictionaries?
A dictionary is a another type of built-in data structure in Python using to store data values in key:value pairs (referred to as an "item").
What is a key:value pair?
The key-value pair concept allows you to retrieve values based on their corresponding keys. The key is mapped to an associated value.
Dictionary Key Constraints
- A
keycannot be a mutable data type (e.g., a list) - Unique within a dictionary
- Cannot be duplicated in the same dictionary (if more the same key is used more than once, then the subsequent entry will overwrite the previous value)
While the keys in a dictionary cannot be modified, the entirety of the key:value pair can be added or removed from a dictionary.
Creating a Dictionary
We can create an instance of a dictionary using curly braces {} with one or more key:value pairs (note: a : is used to separate the key from its associated value)
a_dict = {
key1': 'value1',
key2': 'value2',
key3': 'value3',
...
}
Alternatively, we can construct a dictionary using the built-in dict() function and passing one or more key-value pairs:
# Creating a dictionary with inital key-value pairs
d = dict(
key1 = value1,
key2 = value2,
key3 = value3,
...
)
# Creating a dictionary with key-value pairs
d = dict([
(key1, value1),
(key2, value2),
(key3, value3),
...
])
Clearing a Dictionary
To clear all the entries in a dictionary:
d.clear() # Deletes all entries.
This returns an empty dictionary.