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.

Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)

Let's jump right in.

What is a dictionary

A dictionary is similar to a list. However, we have the added benefit of creating our own indices, known as keys, instead of using the normal numeric index.

Unlike a tuple, a dictionary is mutable, which means we can change the value of items at runtime.

How to declare / initialize a dictionary

Like a set, a dictionary uses two curly braces when initialized. Between the curly braces we specify our keys and values, separated by a comma.

Syntax:
dictionary_name = {
	"key_1" : value_1,
	"key_2" : value_2,
	"key_3" : value_3
}

The colon operator is used between the key and the value to act as an assignment operator.

Example: declare / initialize a dictionary
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.

Syntax:
 dictionary_name["key_name"]
Example: access an item in a dictionary with the key
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 item by its key.

Syntax:
 dictionary_name.get(key)
Example: How_to_do_the_thing
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

We need to access dictionary values within a loop a little differently than we have been up until now. We’re still going to use a for loop , we just have to modify the syntax a bit.

Example:
player = {
	"class" : "Mage",
	"level": 1,
	"hp" : 100,
	"mana" : 100
}

for item in player:
    print(item)

When we run the example above, we can see that the keys are printed instead of the values.

How to access an item in a dictionary loop by key

To access the value instead of the key, we specify the temporary variable as a key.

Syntax:
for item in dictionary_name:
	# access dictionary_name[item]
Example: access an item in a dictionary in a loop with its key
player = {
	"class" : "Mage",
	"level": 1,
	"hp" : 100,
	"mana" : 100
}

for item in player:
    print(player[item])

When we run the example above, we can see that the values in the dictionary are now printed.

To better demonstrate the difference, let’s access both the key and value.

Example:
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 as the indexer (between square brackets), it will print the value associated with the key.

How to access an item in a dictionary loop with the values() function

When we use the values() function in the loop we can access each item with the temporary variable.

Syntax:
for item in dictionary_name.values():
	# access item

The interpreter will access the keys instead of the values so item will refer to the value and not the key.

Example: access an item in a dictionary loop by values()
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 easily, we can use the items() function.

With the items() function we need to use two temporary variables to handle both the keys and the values.

Syntax:
for key, value in dictionary_name.values():
	# access key and/or value
Example: access an item in a dictionary loop by items()
player = {
	"class" : "Mage",
	"level": 1,
	"hp" : 100,
	"mana" : 100
}

for key, value in player.items():
    print(key, ": ", value)

When we run the code above, we can see that the keys and values are printed. 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.

Syntax:
 dictionary_name[key] = new_value
Example: change a value in a dictionary
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 the in keyword with an if statement.

Syntax:
if key in dictionary_name
	# execute code
Example: check if a key exists in a 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 in the dictionary.

We can use the and and or conditional operators to check for multiple keys.

Example:
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()

We can remove an item from a dictionary with the pop() function. With a dictionary we need to specify the key of the item we want to pop.

Syntax:
 dictionary_name.pop(key)
Example: pop() an item from a dictionary
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

We can use the del keyword to remove an item from a dictionary.

Syntax:
 del dictionary_name[key]

We have to specify the key to delete otherwise it will delete the whole dictionary.

Example: del an item from a 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.

Syntax:
 dictionary_name.clear()
Example: clear() a dictionary
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 that 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.

Syntax:
 del dictionary_name
Example: delete a dictionary
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:

FunctionDescription
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.