Python Dictionaries

A dictionary in Python is a way to store Key/Value pairs. They are called associative arrays in other programming languages. Let's see how they work.

You set up a dictionary using curly brackets. The following would set up an empty dictionary:

empty_dictionary = {}

The good thing about dictionaries is that they can store a mixture of values. You can store strings and numbers, for example.

Add the following to a new Python file:

player = {'Name': 'Kranach'}

This sets up a dictionary with one item. The key is Name. The value for that key is Kranach. Notice that the key is a string and therefore surrounded with quote marks. You need a colon next. The colon comes after your quote marks. The value you want for this key comes next. Here, we're storing a person's name as the value for the key.

You add other items in your dictionary after a comma. Add this to your player dictionary:

player = {'Name': 'Kranach', 'Role': 'Warrior'}

The new key is Role. The value for the key is Warrior. We now have a dictionary with two keys. Both values for the two keys are strings. But your dictionary can also hold numbers. Add a third item to your dictionary:

player = {'Name': 'Kranach', 'Role': 'Warrior', 'Strength': 7}

The new key is called Strength. The value for the key is a number, this time.

Your dictionary can hold as many items as you need. Add two more items:

player = {'Name': 'Kranach', 'Role': 'Warrior', 'Strength': 7, 'Luck': 6, 'Stamina': 8}

The new keys are Luck and Stamina. The value are also numbers, 6 and 8.

Let's print something out and see what we've got. Add this for loop:

for key, value in player.items():

print(key, ":", value)

We can use the items methods on our player dictionary. This allows you to cycle through all the items in your dictionary. The parts we need can then be stored in the two variables that we've called key and value. We are then printing theses out, separated by a colon.

Run your code and you should see this in the output window:

Name : Kranach
Role : Warrior
Strength : 7
Luck : 6
Stamina : 8

You can just print the keys:

for key in player:

print(key)

Try the code for yourself. Add a print line as a separator:

print("=========")

Your code will look like this:

A Python dictionary

And the output window will look like this:

The output from a Python dictionary

You can also just print just the values:

for value in player:

print(player[value])

Notice how the value is printed above - with a pair of square brackets after the dictionary name:

player[value]

Another way to get at the value is with the get method:

player.get('Role')

Between round brackets, you type the name of the key whose value you want to access.

Add items to a Python dictionary

You can add items to a Python dictionary. They are not immutable like tuples. Try this. Set up an empty dictionary called enemy:

enemy = {}

To add a new item, you need the dictionary name followed by a pair of square brackets. In between the square brackets, type a new key in quote marks. The value for your new key goes after an equals sign:

enemy['Name'] = "Vilor"

(NOTE: PyCharm will complain about the enemy = {} line. It will underline it in grey and say, "The dictionary creation could be rewritten as a dictionary literal". It's trying to tell you to set up your dictionaries as we did before. You can switch the warning off by going to File > Settings > Editor > Inspections. In the list in the middle, uncheck the item for "Dictionary creation … ". Click Apply and the warning should go away.)

Now add the other dictionary items:

enemy['Role'] = "Warlock"
enemy['Strength'] = 8
enemy['Luck'] = 9
enemy['Stamina'] = 6

Print the keys and values out like before:

print("=========")

for key, value in enemy.items():

print(key, ":", value)

Your code will look like this:

Two dictionaries set up in Python code

Run your program to see the output:

Python dictionary output

Delete items from a Python dictionary

You can delete an item from your dictionary. The syntax is this:

del dictionary_name["KEY_NAME"]

So if you wanted to remove the Luck key from the enemy dictionary, it would be this:

del enemy["Luck"]

This would remove the key and its value.

 

Using Python Dictionaries

You can compare one dictionary value to another. In the code below, we'll compare the Stamina keys and see which one is the greater.

Let's have a title. Add this to your code:

print("------------------------")
print(enemy.get('Role') + " versus " + player.get('Role'))
print("------------------------")

The output would be this, from the three lines of code above:

------------------------------------
Warlock versus Warrior
-------------------------------------

We're using get to get the Role key from both the enemy and player dictionaries.

We can use an if statement to test if the value from the enemy Stamina key is greater than the value from the player Stamina key:

if enemy.get('Stamina') > player.get('Stamina'):

If it is, display a message:

print("Warlock Wins Stamina Battle")

We can test if they are both equal and display a suitable message:

elif enemy.get('Stamina') == player.get('Stamina'):

print("Draw")

If neither of these are true then the player must have won:

else:

print("Warrior Wins Stamina Battle")

Add the if statement to your code and it will look like this:

Using a Python dicitionary

When you run the program, the output would be this with our values:

------------------------
Warlock versus Warrior
------------------------
Warrior Wins Stamina Battle

Try these exercises.

Python Exercise

Test to see who wins a Luck battle between the player and the enemy.

Python Exercise

Test to see who wins a Strength battle between the player and the enemy.

Python Exercise

Add count variables and check to see who wins overall, the enemy or the player. Print a suitable message. Try to print out this:

------------------------
Warlock versus Warrior
------------------------
Kranach the Warrior Defeats Vilor the Warlock

In the above output, you can use dictionary_name.get to get the Names and Roles rather than hardcoding anything.

In the next lesson, you'll look at error checking in Python.

Python Error Checking >