How to Use Dictionaries?
In this lesson, we'll explore how to add, modify, and delete values in dictionaries, and how to use dictionaries with loops in Python.
Adding, Modifying, Deleting Values in a Dictionary
How can we add or modify data in a dictionary that stores a list of friends?
Let's learn how to add new items to, modify, and delete items from dictionaries.
Adding an Element
To add a new element to a dictionary, simply assign a value to a new key in the dictionary.
friends_ages = {
"Alice": 25,
"Bob": 30,
"Charlie": 28
}
# Add David's age
friends_ages["David"] = 26
print(friends_ages)
When the above code is executed, a new entry "David": 26
is added to the friends_ages dictionary, resulting in the output:
{"Alice": 25, "Bob": 30, "Charlie": 28, "David": 26}
Modifying an Element
To modify a specific element in a dictionary, use the key of that element to assign a new value.
For instance, to change Alice
's age to 26, you can write the code as follows:
friends_ages = {
"Alice": 25,
"Bob": 30,
"Charlie": 28
}
# Change Alice's age to 26
friends_ages["Alice"] = 26
print(friends_ages)
Executing this code changes "Alice": 25
to "Alice": 26
.
Deleting an Element
To remove an unnecessary item from a dictionary, use the del
keyword.
For example, to delete Charlie
's information, you can write the code as follows:
friends_ages = {
"Alice": 25,
"Bob": 30,
"Charlie": 28
}
# Delete Charlie's information
del friends_ages["Charlie"]
print(friends_ages)
Now, Charlie
's item is deleted, resulting in the output {"Alice": 25, "Bob": 30}
.
Using Dictionaries with Loops
To examine all keys and values in a dictionary at once, you can use a loop.
Suppose we have a dictionary storing friends' names and ages, as shown below.
To print all information in the friends_ages
dictionary, use the items()
method.
friends_ages = {
"Alice": 25,
"Bob": 30,
"Charlie": 28
}
# Print all friends' names and ages
for name, age in friends_ages.items():
# name is the key, age is the value
print(f"{name} is {age} years old.")
The items()
method makes all items in the dictionary iterable.
For example, using the items()
method on the friends_ages dictionary returns tuples like ("Alice", 25)
, ("Bob", 30)
, ("Charlie", 28)
.
for name, age
unpacks the tuples, assigning keys ("Alice"
, "Bob"
, "Charlie"
) to name
and values (25
, 30
, 28
) to age
.
Using the loop to print all friends' names and ages yields the following output:
Alice is 25 years old.
Bob is 30 years old.
Charlie is 28 years old.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.