Dictionaries in Python

Lists are just one way for Python to store multiple data points. Your next one to learn about should be dictionaries – an unordered list of ‘keys’ and values’ that allow us to give a bit more information about each data point and call for each value in a more logical way than with a list.

This article runs through how dictionaries are created in Python, how we can call for data within them and change them as we need to.

Creating a dictionary

While [lists] use square brackets, {dictionaries} use their curly equivalents. Within them, we use the formula of “key”:”value” to assign information. Just like lists, commas separate our data points. Take a look at the example below that the FC Python kitman created to get ready for matchday:

In [1]:
PlayerOne = {"Name":"Lucasinho",
"Number":8,
"Long Sleeves":True}

PlayerOne
Out[1]:
{'Long Sleeves': True, 'Name': 'Lucasinho', 'Number': 8}

Accessing values in a dictionary

Just like creating a dictionary is easy, so is calling its values. Simply use square brackets after the variable and add the key that you want to know about. This is similar to how we access a list, but we use a key and not a number.

In [2]:
PlayerOne["Number"]
Out[2]:
8

Updating a dictionary and removing values

When assigning new values to keys, or entirely new key-value pairs, you do so exactly like you would assign a variable:

In [3]:
PlayerOne["Long Sleeves"] = False
PlayerOne["Size"] = "Medium"

PlayerOne
Out[3]:
{'Long Sleeves': False, 'Name': 'Lucasinho', 'Number': 8, 'Size': 'Medium'}

Remove a key-value pair with ‘del’. This cannot be undone!

In [4]:
del PlayerOne["Size"]

PlayerOne
Out[4]:
{'Long Sleeves': False, 'Name': 'Lucasinho', 'Number': 8}

Now there is no record of size!

If Lucasinho leaves the club, the kitman has no need to kit him out – so let’s clear out all of his values but keep his name:

In [5]:
PlayerOne.clear()

PlayerOne
Out[5]:
{}

Of course, you could use the earlier ‘del’ for the whole dictionary to banish Lucasinho completely!

Summary

In this article, you have seen a second way to store data in a group with dictionaries. Creating them is easy with curly brackets and keeping our dictionaries up to date is really easy as we have keys to reference our values.

Dictionaries offer new functionality for accessing values in a group that lists do not and will be much more intuitive in many examples of your future code!