Intro
In my previous blog I went over 3 of the built in data sets in Python: lists, tuples, and sets. In this blog we will go over another built in Python data set, dictionaries.
What are Dictionaries?
Dictionaries are used to store value in a key:value pairs. Dictionaries are unordered, do not allow duplicates, and can be changed.
Create a Dictionary
To create a dictionary we use the follow syntax:
variable_name = {key:value}
# example
friend_ages = {
"Rolf": 24,
"Adam": 30,
"Anne": 27
}
Access a dictionary item
To access a dictionary item we use the following syntax:
friend_ages = {
"Rolf": 24,
"Adam": 30,
"Anne": 27
}
print(friend_ages["Adam"]) # 30
If you need to print the entire dictionary you just use print and the dictionary like this:
friend_ages = {
"Rolf": 24,
"Adam": 30,
"Anne": 27
}
print(friend_ages) # {"Rolf": 24,"Adam": 30,"Anne": 27}
Change an Item in a Dictionary
To change an item in a dictionary we use a similar syntax as accessing an item:
friend_ages = {
"Rolf": 24,
"Adam": 30,
"Anne": 27
}
friend_ages["Rolf"] = 21
print(friend_ages["Rolf"]) # 21
Add an Item to a Dictionary
To add an item to a dictionary we use the following syntax:
friend_ages = {
"Rolf": 24,
"Adam": 30,
"Anne": 27
}
friend_ages["Danny"] = 38
print(friends_ages) # {"Rolf": 24,"Adam": 30,"Anne": 27,"Danny":38}
Delete an Item
To delete an item in a dictionary we use the pop()
method:
friend_ages = {
"Rolf": 24,
"Adam": 30,
"Anne": 27
}
friend_ages.pop("Adam")
print(friends_ages) # {"Rolf": 24,"Anne": 27}
Loop Through a Dictionary
Finally to loop through a dictionary we use a for loop:
student_attendance = {"Rolf": 96, "Bob": 80, "Anne": 100}
for student in student_attendance:
print(student) # Rolf, Bob, Anne
# print every key value pair
for student in student_attendance:
print(f"{student}: {student_attendance[student]}")
# Rolf: 96
# Bob: 80
# Anne: 100
Top comments (0)