Understand Dictionaries
In this step, you will learn about dictionaries, a fundamental data structure in Python. Dictionaries are used to store data in key-value pairs, allowing you to quickly retrieve values based on their associated keys.
A dictionary is defined using curly braces {}
. Each key-value pair is separated by a colon :
, and pairs are separated by commas ,
. Here's a simple example:
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
print(my_dict)
To work with dictionaries, let's create a Python file named dictionary_example.py
in your ~/project
directory using the VS Code editor.
Open VS Code, create a new file named dictionary_example.py
in the ~/project
directory, and add the following content:
## Create a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
## Print the entire dictionary
print(my_dict)
Now, execute the Python script using the following command in the terminal:
python ~/project/dictionary_example.py
You should see the following output:
{'name': 'Alice', 'age': 30, 'city': 'New York'}
To access a specific value in the dictionary, use the key within square brackets []
:
name = my_dict["name"]
print(name)
Modify your dictionary_example.py
file to include the following lines:
## Create a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
## Access a value using the key
name = my_dict["name"]
print(name)
Execute the script again:
python ~/project/dictionary_example.py
The output will now be:
Alice
You can also add new key-value pairs to a dictionary:
my_dict["occupation"] = "Engineer"
print(my_dict)
Update your dictionary_example.py
file:
## Create a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
## Add a new key-value pair
my_dict["occupation"] = "Engineer"
print(my_dict)
Run the script:
python ~/project/dictionary_example.py
The output will be:
{'name': 'Alice', 'age': 30, 'city': 'New York', 'occupation': 'Engineer'}
Dictionaries are mutable, meaning you can change the value associated with a key:
my_dict["age"] = 31
print(my_dict)
Modify your dictionary_example.py
file:
## Create a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
## Change the value of an existing key
my_dict["age"] = 31
print(my_dict)
Execute the script:
python ~/project/dictionary_example.py
The output will be:
{'name': 'Alice', 'age': 31, 'city': 'New York'}
Understanding dictionaries is crucial for working with structured data in Python. They provide a flexible and efficient way to store and retrieve information.