Dictionaries
Creating a dictionary
# create empty dict (two ways)
empty_dict = {}
empty_dict = dict()
# Create pre-filled dict
some_dict = {"key1": "value1", "key2": "value2"}
# more readable formatting (expecially for lots of key/value pairs)
player = {
"health": 100,
"name": "Frankie",
"class": "Wizard",
}
Accessing a value in a dictionary
Similar to a list, instead of accessing the value by the index, you access it using the key (label) you defined:
player = {
"health": 100,
"name": "Frankie",
"class": "Wizard",
}
print(player["health"]) # outputs 100
Warning
When using dictionaries in f-strings, you cannot use the same quote types.
print(f"Health: {player["health"]}") # WON'T WORK
print(f"Health: {player['health']}") # works
Adding a value to a dictionary
player = {
"health": 100,
"name": "Frankie",
"class": "Wizard",
}
player["strength"] = 50 # adds key/value strength: 50
print(player["strength"])
Modifying a value in a dictionary
player = {
"health": 100,
"name": "Frankie",
"class": "Wizard",
}
player["health"] = 90 # changes health to 90
print(player["health"])
player["health"] += 10 # increases health back to 100
print(player["health"])
Removing a value from a dictionary
player = {
"health": 100,
"name": "Frankie",
"class": "Wizard",
"not-needed": "Then why is it here?"
}
del player["not-needed"]
print(player["not_needed"]) # raises KeyError (key doesn't exist anymore)
Iterating through dictionary keys
The .keys()
method will return a collection of all the dictionary’s keys.
player = {
"health": 100,
"name": "Frankie",
"class": "Wizard",
}
for key in player.keys():
print(key)
"""outputs:
health
name
class
"""
Iterating through dictionary values
The .values()
method will return a collection of all the dictionary’s values.
player = {
"health": 100,
"name": "Frankie",
"class": "Wizard",
}
for value in player.values():
print(value)
"""outputs:
100
Frankie
Wizard
"""
Iterating through dictionary keys and values
The .items()
method will return a collection of all the dictionary’s keys and values paired together. In our example, it would be equivalent to the folling list:
[("health", 100), ("name", "Frankie"), ("class", "Wizard")]
Essentially, a collection of tuples. FOr this, you will need two loop variables: key and value.
player = {
"health": 100,
"name": "Frankie",
"class": "Wizard",
}
for key, value in player.items():
print(key, value)
"""outputs:
health 100
name Frankie
class Wizard
"""