Understand Dictionary Values
In this step, you will learn about dictionary values in Python. Dictionaries are a fundamental data structure that store data in key-value pairs. Understanding how to access and manipulate these values is crucial for working with dictionaries effectively.
First, let's create a simple dictionary:
## Create a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
## Print the dictionary
print(my_dict)
Create a file named dictionary_example.py
in your ~/project
directory using the VS Code editor. Copy and paste the above code into the file.
Now, run the script using the following command in the terminal:
python dictionary_example.py
You should see the following output:
{'name': 'Alice', 'age': 30, 'city': 'New York'}
To access the values in a dictionary, you can use the keys. For example, to access the value associated with the key "name"
, you would use my_dict["name"]
.
Let's modify the dictionary_example.py
file to access and print the values:
## Create a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
## Access and print the values
print(my_dict["name"])
print(my_dict["age"])
print(my_dict["city"])
Save the changes to dictionary_example.py
and run it again:
python dictionary_example.py
The output should now be:
Alice
30
New York
You can also use the .values()
method to get a collection of all the values in the dictionary. This method returns a view object that displays a list of all the values in the dictionary.
Modify the dictionary_example.py
file to use the .values()
method:
## Create a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
## Get the values
values = my_dict.values()
## Print the values
print(values)
Save the changes to dictionary_example.py
and run it again:
python dictionary_example.py
The output should now be:
dict_values(['Alice', 30, 'New York'])
As you can see, the .values()
method returns a view object containing all the values in the dictionary. You can iterate over this view object to access each value individually, which you will learn in the next steps.