Enchanted Code

Dictionaries In Python

5 minutes read

Intro

This tutorial will teach you about the dictionary data-structure in Python.

Requirements

  • Know basics of Python 3 if not read here
  • Knowledge of Computer Science data-structures will help

What are they?

A dictionary is an ordered collection of key-value pairs. Each key added to a dictionary has to be unique, the value assigned to a key does not have to be unique. In Python a dictionary’s key can be any object (objects will be covered in a later tutorial) that is marked “hashable”. For example they could be (but not limited to) an int, string or float data-type. The keys can also be of different data-types inside one dictionary.

Creation

First let’s start off by creating a dictionary. Our first dictionary will be simple; it will have a players name as the key and a score (int) as the value.

To create a dictionary we first have to assign it to a variable, in our case it will be called “player_scores”. We then use curly braces to define we are making a dictionary. In our dictionary we will have 3 players these players will be called “Bob”, “Steve” and “Dave”. As you can see our dictionary keys will be strings. Then to create the key-pair we use the colon character to give a value to our key. When we have multiple key-value pairs we use a comma to separate each one.

1
2
player_scores = {"Bob": 10, "Steve": 12, "Dave": 5}
print(player_scores)

When our program is run will will get the dictionary output. This is shown below:

1
{'Bob': 10, 'Steve': 12, 'Dave': 5}

Accessing Elements

We can access each value in a dictionary by its key, we can achieve this similar to how we access lists.

As you can see from the code below we can access a value by using square brackets, like we do when accessing an index in a list, however this time instead of passing an index we use a value that is a key in the dictionary.

1
2
steve_score = player_scores["Steve"]
print(steve_score)

There are multiple other ways to access a value inside a dictionary. For example using the .get() function

When this is run we should get the output of: 12.

Modifying Elements

Also like a list we can modify a value in a dictionary by using square brackets, and then instead of an index we use a key. Like shown below:

1
2
player_scores["Dave"] = 100
print(player_scores)

When this is run we should see that the “Dave” key is now equal to 100.

1
{'Bob': 10, 'Steve': 12, 'Dave': 100}

Adding Elements

We can also add a new key-value pair to the dictionary. You may notice that we are using the same statement as modifying a element. However in this case we know that that key-value pair doesn’t exist.

1
2
player_scores["John"] = 2
print(player_scores)

When the code above is run we get the following output:

1
{'Bob': 10, 'Steve': 12, 'Dave': 100, 'John': 2}

We can see that it has however added a new key-value pair to the dictionary.

Removing Elements

Let’s delete an element from the dictionary. We can delete elements several ways. Like a list we can use “.pop” and the “del” keyword.

Del

This example will show you how to delete an element using the “del” keyword.

1
2
del player_scores["John"]
print(player_scores)

As you can see you simply place the “del” keyword when accessing the player_scores dictionary by a key. When this is run you should get the following output:

1
{'Bob': 10, 'Steve': 12, 'Dave': 100}

There are other ways of deleting key-value pairs not covered in this tutorial.

Clear

A dictionary has a special function that is not included with a list, this method will allow us to clear a dictionary of all key-value pairs.

1
2
player_scores.clear()
print(player_scores)

As you can see when you run this code you will end up with an empty dictionary. You will get the following output:

1
{}

Iteration

We can also iterate over the keys in a dictionary.

Iteration is covered in another tutorial here.

1
2
3
4
player_scores = {"Bob": 10, "Steve": 12, "Dave": 5, "John": 20}

for key in player_scores:
    print(key, "score is", player_scores[key])

As you can see when run we get each key. We can then access the value by using the method shown before in the tutorial.

1
2
3
4
Bob score is 10
Steve score is 12
Dave score is 5
John score is 20

Extras

Dictionaries in Python come with some useful functions we can call on the object. Here I will show extracting the keys and values.

Looking at this code you may notice .keys() and .values() are being converted into a list, this is because Python returns an iterable that cannot be accessed by index; so I am converting them into lists.

Try removing the list conversion to see what happens

1
2
3
4
5
6
7
8
9
player_scores = {"Bob": 10, "Steve": 12, "Dave": 5, "John": 20}

keys = list(player_scores.keys())
values = list(player_scores.values())

print(keys)
print(values)

print(keys[0])

As you can see from the output we have the keys, values and the first key displayed.

1
2
3
['Bob', 'Steve', 'Dave', 'John']
[10, 12, 5, 20]
'Bob'

Research

There is much more to learn about dictionaries, have a look at the official Python documentation for more in-depth knowledge here.

See Also

Buy Me A Coffee