8. Arrays And Dictionaries

Ahoy! Time to learn about arrays and dictionaries. Let’s get started.

You know that a variable can hold a single value of a certain data type, right? But what if we wanted to store a collection of related values in a variable? Say we want to build a game. We would need to store the names of several players in a players variable, right? Arrays and dictionaries to the rescue!

Arrays and dictionaries are part of a broader topic known as data structures. The study of data structures is beyond the scope of this lessons and at some point, we’ll need to learn more about them, but for the time being, let’s concentrate on these two data structure types.

Arrays

Look at the following example and see if you can identify what’s wrong with writing code like this (we removed the on the screen part for the sake of brevity. We know that we want to display information on a screen):

player1 = "Mickey"
player2 = "Donald"
player3 = "Bob"

Display player1
Display player2
Display player3

Firstly, we’re repeating ourselves too much! What would happen if we wanted to add a player4 to our program? We would need to add it to the existing code like this:

player1 = "Mickey"
player2 = "Donald"
player3 = "Bob"
player4 = "Cersei"

Display player1
Display player2
Display player3
Display player4

This is clearly a case where an array can save the day! We need to store these player names somewhere, right? An array is a special type of variable that can contain several values. Let’s see what the pseudocode would look like:

players[] = ["Mickey", "Donald", "Bob", "Cersei"]

Display players[0]
Display players[1]
Display players[2]
Display players[3]

By adding square brackets ([]) to the players variable, we told the computer that we want it to be an array of values. To store multiple values in our players array, we assigned and inserted comma-separated values between the square brackets.

To make use of specific individual value(s) within the array, we called the players variable, passing in the index of the value we want between square brackets.

Caution: most programming languages use a zero-based index! This means that the first element in the array is referenced by the index 0players[0] means the first value in the players array.

For example, to use the player Donald, who is in the 2nd position in our players array, we would call players[1]. Don’t get confused by the 1 index. In a zero-based indexing system, the first player (Mickey) would be players[0].

array

In an array, we can also store a range. Check this out:

fewNumbers[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

The array variable fewNumbers stores integers from 1 to 10. This is a range. It probably won’t surprise you to know that there’s a more efficient way of expressing a range! We can use the to keyword, which means we avoid having to type each integer manually. Like so:

fewNumbers[] = [1 to 10]

Editing Values In An Array

If you’ve already defined an array in your code, you can always add more values to it or modify existing ones. Consider this:

someNumbers[] = [1, 8, 21, 5]
someNumbers[1] = 10
someNumbers[4] = 123
someNumbers[5] = 11
someNumbers[4] = 321

Could you list the values that are now in the someNumbers array? Of course!

1, 10, 21, 5, 321, 11

What did you do here?

  1. You assigned 1,8,21,5 to someNumbers
  2. Using its index, you changed the value 8 to now be 10
  3. You added one more value at the end of the array: 123 that is now at index 4
  4. You again added one more value at the end of the array: 11 that is now at index 5
  5. Using its index, you changed the value 123 to 321

That’s some serious array manipulation, right there! Nice one!

Copying Arrays

To assign the values contained within an array to another array you’d use the assignment operator (=) just like with a regular, single value variable:

superheroes[] = ["Antman", "Squirrel Woman", "The Fantastic Platypus"]
persons = superheroes

Note that persons is now an array. Why didn’t we use the square brackets after its name ([])? Because of type inference. Remember type inference?

Iterating Through An Array

By using an array, we removed some repetition from the code. Still, we needed to call Display four times for our four players. Surely there’s a better way to do this? Of course! By using a special type of loop construct known as a foreach loop. Let’s look at the code:

players[] = ["Mickey", "Donald", "Bob", "Cersei"]

foreach player in players {
  Display player
}

Without us explaining, we’re pretty sure you understood what this code means and what it would do. Let’s put it in English:

  1. Declare an array variable named players and assign four strings to it
  2. For each player within the players array variable, display the value

The foreach part is the beginning of a loop, much like a regular loop such as Do 3 times. Then, between the curly braces ({ }), we have the block of statements that should be executed as part of the loop, in this case, we only have one: Display player. If we use the Do construct for our loop, we need to specify how many times we want the loop block to be run. With a foreach construct, we don’t specify the number of times it needs to run. Instead, it’s implicit that we’re actually telling the computer to loop as long as there are values in the array.

Here’s a quick challenge for you: could you write a program that displays each number from 1 to 100?

Try do it without peeking at the answer below!

Did you write something like this?

numbers[] = [1 to 100]

foreach number in numbers {
  Display number
}

Easy? We’ll see many arrays in future code examples and even more once we start learning a concrete programming language. It may still be a bit fuzzy at this stage. That’s perfectly normal. If you understand what purpose arrays serve (storing multiple related values in a collection), you’re good to go. Speaking of which, let’s look at another data structure: key-value pairs known as a dictionary.

Dictionaries

dictionary, sometimes known as an associative array, behaves like a regular array, except it’s not index-based. Instead, each value is based on an associated key. Let’s use an example to see the problems dictionaries can solve. Let’s assume that we’d like to store various values representing a person in an array such as FirstnameLastnameCityCountry:

onePerson[] = ["Aleqa", "Lyberth", "Nuuk", "Greenland"]

Unless you’re well versed in Greenlandic culture, you’d be hard pressed to say which of these string values in the onePerson array is the firstname, the lastname and the city! And even if you figured it out, if you needed to reference the city (the 3rd item in the array), you’d be obliged to call it by its index, like so: onePerson[2](remember that arrays have zero-based index, so the 3rd item has the index 2. This wasn’t a typo!).

If you define multiple arrays in your program, keeping track of which index represents which type of value would quickly become a nightmare. If only we could change the index number to a word… Fear not; we can! That’s what dictionaries are for. Consider this:

onePerson[] = [Firstname: "Aleqa", Lastname: "Lyberth", City: "Nuuk", Country: "Greenland"]

Much easier to read, right? To construct a dictionary, we use key-value pairs. Now, if we want to reference the onePerson lastname, we can use the Lastname key rather than its index, this way: onePerson[Lastname] would return Lyberth.

dictionary

Editing Values In A Dictionary

Like the array, values can be added and edited in a dictionary:

batman[] = [RealName: "Bruce Wayne", FavoriteColor: "Black"]
batman[RealName] = "Bruce Pedro Wayne"
batman[Vehicle] = "Bat-car"

Now, if we list the key-value pairs in the batman dictionary, we’d have:

RealName: Bruce Pedro Wayne
FavoriteColor: Black
Vehicle: Bat-car

The only (pedantic) thing to note here is that black is not a color!

Copying A Dictionary

Nothing too complicated here. We can copy a dictionary in exactly the same way as we copied an array:

blogPost = [Title: "An interesting title", Content: "I don't have much to say at this moment"]
newPost = blogPost

Now blogPost and newPost have the exact same content.

Iterating Through A Dictionary

Iterating through a dictionary is done with a foreach loop, too! The difference is that we can also access the key, not only the value within our loop block. Time for an example:

someCar[] = [Brand: "Ford", Wheels: "4", Doors: "4", Model: "Focus"]

foreach key, value in someCar {
  Display key + " " + value
}

This code would output the following result on your screen:

Brand Ford
Wheels 4
Doors 4
Model Focus

Just note that in our foreach declaration, we used two variables, key and value, instead of just one, as we did with foreach iterating through an array.

Let’s quickly recap how to iterate through an array as well as a dictionary:

Looping Through The Values Of An Array:

foreach value in myArray {
  Do something interesting with the value
}

Looping Through A Dictionary:

foreach key, value in myDictionary{
  Do something interesting with the key and/or the value
}

Summary

In this short lesson, we’ve met two common data structures: the array and the dictionary. Both serve the purpose of storing related values in a single variable. Arrays are accessed through their index, which in most programming languages, is zero-based (meaning that the first item in an array is always at the index 0). Arrays can also be used to store a range of numbers we specify with the keyword to in pseudocode.

Dictionaries are key-value pairs. Their values are associated with a key that we use when we want to reference a particular value. We’ve also met a new kind of loop known as the foreach loop that is used to iterate over all the values in an array as well as key-values in a dictionary.

Phew! That was a lot. Make sure you:

  • Understand everything we’ve gone through
  • Treat yourself to something sweet!

Important Words

  • Data structure
  • Collection
  • Array
  • Range
  • Dictionary
  • Index
  • Zero-based index
  • Foreach loop
Exercise

Using pseudocode, create a program that displays information about yourself. Store your information in a dictionary and have the Main function run a ShowInformation function displaying your info. Of course, share it with the community in the comments below so that everybody can get to know you better, while reviewing your pseudocode!

Share to friends