Associative Array

An associative array, dictionary, map, or symbol table all refer to the same thing, usually, in computer science. It is an abstract data type composed of a collection of key and value pairs, such that each possible key appears at most once in the collection. The key and value can usually be of almost any type, although usually the key is represented by a string. (If it was an integer, then you would just have an array!). The data type usually comes with operators like, the addition of a pair to the collection, the removal of a pair from the collection, the modification of an existing pair, the lookup of a value associated with a particular key.

You can think of associative arrays like a list of phone numbers. In this list, you can look up a person’s name by finding their phone number. The name is the value and the number is the key. This list would look like the following table:

Phone Number

Name

1-203-456-4657

John Doe

1-964-725-5617

Jane Smith

1-275-486-8562

Daniel Brown

1-347-374-3412

John Doe

Associative arrays have two important properties. Every key can only appear once, just like every phone number can only appear once in a directory. And, every key can only have one value, just like every phone number can only refer to one person. It is possible that two people can have the same name in this list, so it’s important to remember that a given value can appear more than once in an associative array.

Code for Creating an Associative Array

// No associative arrays in C
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Copyright (c) 2020 St. Mother Teresa HS All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program uses a map

#include <iostream>
#include <map>

int main() {
    // this function uses a map
    std::string airportName = "";

    // an empty map
    std::map<std::string, std::string> airports;

    // a map filled with data
    std::map<char, int> someInfo = {
        {'a', 1},
        {'b', 2},
        {'c', 3},
    };

    // adding items
    airports.insert(std::pair<std::string, std::string>("YYZ", "Toronto Pearson"));
    airports.insert(std::pair<std::string, std::string>("YOW", "Ottawa Canada"));
    airports["DUB"] = "Dublin Ireland";
    airports["LHR"] = "London Heathrow";

    std::cout << "All the airports:" << std::endl;
    for (auto const &pair : airports) {
        std::cout << "The airport code is " << pair.first << " for " << pair.second << std::endl;
    }
    std::cout << " " << std::endl;

    std::cout << "Type in an airport code: ";
    std::cin >> airportName;
    std::cout << " " << std::endl;

    if (airports.count(airportName) > 0) {
        std::cout << "The name of the airport you chose is " << airports[airportName];
    } else {
        std::cout << "That airport is not in the airport's dictionary.";
    }

    std::cout << " " << std::endl;

    std::cout << "\nDone." << std::endl;
    return 0;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/* Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program uses a dictionary
*/

using System;
using System.Collections.Generic;

/*
 * The Program class
*/
class Program {
    static void Main() {
        // this function uses a dictionary
        string airportName;

        // an empty dictionary
        Dictionary<string, string> airports = new Dictionary<string, string>();

        // a dictionary filled with data
        Dictionary<char, int> someInfo = new Dictionary<char, int>() {
            {'a', 1},
            {'b', 2},
            {'c', 3}
        };

        // adding items
        airports["YYZ"] = "Toronto Pearson";
        airports["YOW"] = "Ottawa Canada";
        airports["DUB"] = "Dublin Ireland";
        airports["LHR"] = "London Heathrow";

        Console.WriteLine("All the airports:");
        foreach (var pair in airports) {
            Console.WriteLine("The airport code is " + pair.Key + " for " + pair.Value);
        }
        Console.WriteLine();

        Console.Write("Type in an airport code: ");
        airportName = Console.ReadLine();
        Console.WriteLine();

        if (airports.ContainsKey(airportName)) {
            Console.WriteLine("The name of the airport you chose is " + airports[airportName]);
        } else {
            Console.WriteLine("That airport is not in the airport's dictionary.");
        }

    Console.WriteLine("\nDone.");
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
 * Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program uses a map
 */

package main

import (
	"fmt"
)

func main() {
	// this function uses a map

	var airportName string

	// an empty map
	airports := make(map[string]string)

	/*
	// a map filled with data
	someInfo := map[byte]int{
		'a': 1,
		'b': 2,
		'c': 3,
	}
	*/

	// adding items
	airports["YYZ"] = "Toronto Pearson"
	airports["YOW"] = "Ottawa Canada"
	airports["DUB"] = "Dublin Ireland"
	airports["LHR"] = "London Heathrow"

	fmt.Println("All the airports:")
	for code, name := range airports {
		fmt.Printf("The airport code is %s for %s\n", code, name)
	}
	fmt.Println()

	fmt.Print("Type in an airport code: ")
	fmt.Scanln(&airportName)
	fmt.Println()

	if name, ok := airports[airportName]; ok {
		fmt.Println("The name of the airport you chose is", name)
	} else {
		fmt.Println("That airport is not in the airport's dictionary.")
	}

	fmt.Println("\nDone.")
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*
 * This program uses a map
 *
 * @author  Mr Coxall
 * @version 1.0
 * @since   2020-09-01
 */

import java.util.Scanner;
import java.util.HashMap;
import java.util.Map;

public class Main {
  public static void main(String[] args) {
    // this function uses a uses a map
    String airportName;

    // an empty map
    Map<String, String> airports = new HashMap<>();

    // a map filled with data
    Map<Character, Integer> someInfo = new HashMap<>();
    someInfo.put('a', 1);
    someInfo.put('b', 2);
    someInfo.put('c', 3);

    // adding items
    airports.put("YYZ", "Toronto Pearson");
    airports.put("YOW", "Ottawa Canada");
    airports.put("DUB", "Dublin Ireland");
    airports.put("LHR", "London Heathrow");

    System.out.println("All the airports:");
    for (Map.Entry<String, String> entry : airports.entrySet()) {
        System.out.println("The airport code is " + entry.getKey() + " for " + entry.getValue());
    }
    System.out.println();

    Scanner scanner = new Scanner(System.in);
    System.out.print("Type in an airport code: ");
    airportName = scanner.nextLine();
    System.out.println();

    if (airports.containsKey(airportName)) {
        System.out.println("The name of the airport you chose is " + airports.get(airportName));
    } else {
        System.out.println("That airport is not in the airport's dictionary.");
    }

    // close the Scanner object
    scanner.close();
    System.out.println("\nDone.");
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/* Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program uses a map
 */

const prompt = require("prompt-sync")()

// this function uses a map
let airportName;

// an empty map
const airports = new Map();

// a map filled with data
const someInfo = new Map([
  ['a', 1],
  ['b', 2],
  ['c', 3],
]);

// adding items
airports.set("YYZ", "Toronto Pearson");
airports.set("YOW", "Ottawa Canada");
airports.set("DUB", "Dublin Ireland");
airports.set("LHR", "London Heathrow");

console.log("All the airports:");
for (let [code, name] of airports) {
  console.log(`The airport code is ${code} for ${name}`);
}
console.log();

airportName = prompt("Type in an airport code: ");
console.log();

if (airports.has(airportName)) {
  console.log("The name of the airport you chose is", airports.get(airportName));
} else {
  console.log("That airport is not in the airport's dictionary.");
}

console.log("\nDone.")
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/usr/bin/env python3
"""
Created by: Mr. Coxall
Created on: Sep 2020
This module uses an associative array
"""


def main() -> None:
    """The main() this function uses an associative array, returns None."""

    airports = {}
    some_info = {'item1': 1,
                 'item2': 2,
                }

    # adding items
    airports['YYZ'] = "Toronto Pearson"
    airports['YOW'] = "Ottawa Canada"
    airports['DUB'] = "Dublin Ireland"
    airports['LHR'] = "London Heathrow"

    # input & process
    print("All the airports:")
    for key, value in airports.items():
        print(f"The airport code is {key} for {value}.")
    print("")

    airport_name = input("Type in an airport code: ")
    if airport_name in airports:
        print(f"The name of the airport you chose is {airports[airport_name]}.")
    else:
        print("That airport is not in the airport's dictionary.")

    print("\nDone.")


if __name__ == "__main__":
    main()

Example Output

Code example output