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:
PlayerOne = {"Name":"Lucasinho",
"Number":8,
"Long Sleeves":True}
PlayerOne
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.
PlayerOne["Number"]
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:
PlayerOne["Long Sleeves"] = False
PlayerOne["Size"] = "Medium"
PlayerOne
Remove a key-value pair with ‘del’. This cannot be undone!
del PlayerOne["Size"]
PlayerOne
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:
PlayerOne.clear()
PlayerOne
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!