A dictionary (also referred to as an associative array, or a hash table) in Python is another structure we can use to store a collection of values. However, rather than referencing these values using an index (or position) like we did with lists, we use a “key”, which is a custom identifier. We call these elements in a dictionary “key-value pairs”. Dictionaries can contain elements of different data types.
We create a dictionary using curly braces { }, and separate each individual key and value using a colon. For example:
To access a value in a dictionary, we put the corresponding key in hard brackets [] (similar to how we use an index to access items in a list). For example:
You can also use the key to add or update values using the assignment (=) operator:
person1 = {"name": "Maria", "age": 25, "city": "Miami"}
# update a value:
person1["age"] = 26
# add a new key-value pair
person1["occupation"] = "Teacher"
Dictionaries are helpful to use when we need an additional way to refer to values in a data structure other than just by an index, and to manage the complexity of a program.