Python Dictionary Collection Tutorial
In this tutorial we learn about one of Python's more complex collection data types, dictionaries. We cover declaring a dictionary with key:value pairs as well as how to access, change and remove items.
Finally, we cover dictionary constructors, and common set functions.
- What is a dictionary
- How to declare / initialize a dictionary
- How to access a value in a dictionary
- How to access items with a loop
- How to change a value in a dictionary
- How to check if a key exists in a dictionary
- How to remove items from a dictionary
- How to clear a dictionary
- How to delete a dictionary
- Dictionary Functions
- Summary
What is a dictionary
A dictionary is similar to a list collection. However, we have the added benefit of creating our own indices (known as keys) instead of using the normal numeric index.
Unlike a tuple collection, a dictionary is mutable. This means we can change the value of items at runtime.
How to declare/initialize a dictionary
Like a set collection, a dictionary uses an object with key:value pairs, separated with a comma.
dictionary_name = {
"key_1": value_1,
"key_2": value_2,
"key_3": value_3
}
The key names in the object must be strings, but the values may be of any type we need.
player = {
"class": "Mage",
"level": 1,
"hp": 100,
"mana": 100
}
How to access a value in a dictionary
Python allows us several ways to access data from a dictionary.
- key indexer
- get() function
How to access an item in a dictionary by its key
To access a value in a dictionary, we can use the key that we specified between square brackets.
dictionary_name["key_name"]
player = {
"class": "Mage",
"level": 1,
"hp": 100,
"mana": 100
}
print("Player class: " + player["class"])
When we run the example above, we can see that the value that is associated with the “class” key is displayed.
How to access an item in a dictionary with the get() function
We can use the get() function to access an item by its key.
dictionary_name.get(key)
player = {
"class": "Mage",
"level": 1,
"hp": 100,
"mana": 100
}
print("Player class: " + player.get("class"))
When we run the example above, we can see that the output printed is the value that is associated with the “class” key.
How to access items with a loop
Because we’re working with key:value pairs, looping over a dictionary is a little different than we’re used to.
As an example, let’s see what happens when we use a regular for loop.
player = {
"class": "Mage",
"level": 1,
"hp": 100,
"mana": 100
}
for item in player:
print(item)
When we run the example, the keys are printed instead of the values.
In most cases we’ll want the values, not the keys. Python gives us 3 ways to access them.
- With the indexer.
- With the values() function.
- With the items() function.
How to access an item in a dictionary loop with the indexer
If we want the value of a dictionary item, we use the temporary variable as the index.
for item in dictionary_name:
# access dictionary_name[item]
player = {
"class": "Mage",
"level": 1,
"hp": 100,
"mana": 100
}
for item in player:
print(player[item])
This time when we run the example, the values are printed to the console and not the keys.
To better demonstrate the difference, let’s access the key and value.
player = {
"class": "Mage",
"level": 1,
"hp": 100,
"mana": 100
}
for item in player:
print("Key: ", item, " | Value: ", player[item])
When we run the example above, we can see that the temp variable is the key.
If we use the key on its own it will print the key, but if we use the key in the indexer, it will print the value associated with the key.
How to access an item in a dictionary loop with the values() function
To use the values() function in a loop, we chain it onto the dictionary name.
for item in dictionary_name.values():
# access item
note The interpreter will access the key and return the value. So item will refer to the value, not the key.
player = {
"class": "Mage",
"level": 1,
"hp": 100,
"mana": 100
}
for item in player.values():
print(item)
When we run the example above only the values are printed.
How to access an item in a dictionary loop with the items() function
If we want to access both keys and values, we chain the items() function onto the dictionary name.
To handle the keys and values, we specify two temporary variables in the loop.
for key, value in dictionary_name.values():
# access key and/or value
The first variable will be the key and the second will be the value.
player = {
"class": "Mage",
"level": 1,
"hp": 100,
"mana": 100
}
for key, value in player.items():
print(key, ": ", value)
When we run the code above, it works as expected.
tip This is the most common way to access a dictionary because it’s so fast and easy.
How to change a value in a dictionary
We can change the value of an item by using its key and then assigning it a new value.
dictionary_name[key] = new_value
player = {
"class": "Mage",
"level": 1,
"hp": 100,
"mana": 100
}
player["level"] = 2
print("Congratulations! You have reached level ", player["level"])
When we run the example above we can see that the number associated with the “level” key has changed.
How to check if a key exists in a dictionary
To check if a key exists in the dictionary, we use a if..in statement.
if key in dictionary_name
# execute code
As an example, let’s check if the “hp” key exists in the dictionary.
player = {
"class": "Mage",
"level": 1,
"hp": 100,
"mana": 100
}
if "hp" in player:
print("Our player has HP")
When we run the example above our message is printed because the key “hp” does exist.
We can also use the and and or conditional operators to check for multiple keys.
player = {
"class": "Mage",
"level": 1,
"hp": 100,
"mana": 100
}
if "hp" and "mana" in player:
print("Our player has HP and Mana")
if "hp" or "mana" in player:
print("Our player has HP or Mana")
When we run the example above, our messages are printed because the keys “hp” and “mana” exist in our dictionary.
How to remove items from a dictionary
We have several ways to remove an item from a dictionary.
- pop() function.
- del keyword.
How to remove an item from a dictionary with pop()
To remove an item from a dictionary, we can use the pop() function and specify the key of the item we want to remove.
dictionary_name.pop(key)
As an example, let’s remove the “mana” key.
player = {
"class": "Mage",
"level": 1,
"hp": 100,
"mana": 100
}
player.pop("mana")
for key, value in player.items():
print(key, ": ", value)
When we run the example above, we can see that “mana” is no longer inside the dictionary.
How to remove an item from a dictionary with del
Another way to remove an item from a dictionary is to use the del keyword and specify the key of the item we want to remove.
del dictionary_name[key]
note If we don’t specify a key, it will delete the entire dictionary.
player = {
"class": "Mage",
"level": 1,
"hp": 100,
"mana": 100
}
del player["mana"]
for key, value in player.items():
print(key, ": ", value)
When we run the example above, we can see that “mana” was deleted from the dictionary.
How to clear a dictionary
We can clear the whole dictionary with the clear() function.
dictionary_name.clear()
player = {
"class": "Mage",
"level": 1,
"hp": 100,
"mana": 100
}
player.clear()
for key, value in player.items():
print(key, ": ", value)
When we run the example above, nothing will be printed because the dictionary has no items.
note The clear function does not delete the dictionary. It still exists, it’s just empty.
How to delete a dictionary
To completely delete a dictionary we use the del keyword.
del dictionary_name
player = {
"class": "Mage",
"level": 1,
"hp": 100,
"mana": 100
}
del player
for key, value in player.items():
print(key, ": ", value)
When we run the example above, and try to access the deleted dictionary, we’ll get a NameError.
Because the dictionary has been deleted, its name will not exist anymore.
Dictionary Functions
The following table shows some common functions used with dictionaries:
Function | Description |
---|---|
clear() | Removes all the items from a dictionary. |
copy() | Returns a full copy of a dictionary. |
fromkeys() | Returns a dictionary with the specified keys and values |
get() | Returns the value of a specified key |
items() | Returns a list containing a tuple for each key value pair |
keys() | Returns a list containing a dictionary’s keys |
pop() | Removes the element with a specified key |
setdefault() | Returns the value of a specified key. If the key does not exist: insert the key, with the specified value |
update() | Updates a dictionary with the specified key-value pairs |
values() | Returns a list of all the values in a dictionary |
Summary: Points to remember
- A dictionary is similar to a list, but supports custom keys instead of index numbers.
- We store dictionary items by writing key:value pairs, separated by commas, between curly braces.
- We access elements in a dictionary by specifying its key in the indexer. We can also use the get() , values() , or items() functions to retrieve dictionary items.
- Dictionaries are mutable. We can change their values by assigning a new value to the key that corresponds to the element’s location in the list.
- We check if an item exists in a dictionary with an if..in statement.
- We remove items from a list by using the pop() function or del keyword.
- We clear all values from a dictionary with the clear() function. This will only empty the dictionary, not delete it entirely.
- We delete a dictionary entirely with the del keyword.