Dictionaries

A dictionary is a collection of key-value pairs. It is a data structure that allows us to store and retrieve values based on their associated keys. Think of a dictionary as a real-life dictionary, where you can look up a word (key) and find its definition (value).

To create a dictionary, you use curly braces {} and separate the key-value pairs with colons :. Here's an example:

student = {"name": "John", "age": 15, "grade": 9}

In this example, we created a dictionary called student that contains three key-value pairs. The keys are "name", "age", and "grade", and the corresponding values are "John", 15, and 9.

You can access the values in a dictionary by their keys. For example:

print(student["name"])  # Output: "John"
print(student["age"])  # Output: 15

In this code, we use square brackets after the dictionary name to access specific values. student["name"] gives us the value associated with the key "name", which is "John", and student["age"] gives us the value associated with the key "age", which is 15.

You can also change the value of a key in a dictionary by assigning a new value to it. For example:

student["grade"] = 10
print(student)  # Output: {"name": "John", "age": 15, "grade": 10}

In this code, we assign the value 10 to the key "grade" in the dictionary. After this change, the dictionary will be {"name": "John", "age": 15, "grade": 10}.

Dictionaries in Python are very flexible and can hold different types of values as keys and values. For example, you can have strings, numbers, or even other dictionaries as keys or values.

Here's an example of a dictionary with different types of keys and values:

person = {"name": "Alice", "age": 25, "is_student": False}

In this dictionary, the key "name" has a string value, the key "age" has a number value, and the key "is_student" has a boolean value (True or False).

These are just a few basic operations you can perform with dictionaries in Python. There are many more methods and functionalities available for working with dictionaries, such as adding new key-value pairs, removing key-value pairs, and looping through the keys or values.