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// Copyright (c) 2020 St. Mother Teresa HS All rights reserved.
2//
3// Created by: Mr. Coxall
4// Created on: Sep 2020
5// This program uses a map
6
7#include <iostream>
8#include <map>
9
10int main() {
11 // this function uses a map
12 std::string airportName = "";
13
14 // an empty map
15 std::map<std::string, std::string> airports;
16
17 // a map filled with data
18 std::map<char, int> someInfo = {
19 {'a', 1},
20 {'b', 2},
21 {'c', 3},
22 };
23
24 // adding items
25 airports.insert(std::pair<std::string, std::string>("YYZ", "Toronto Pearson"));
26 airports.insert(std::pair<std::string, std::string>("YOW", "Ottawa Canada"));
27 airports["DUB"] = "Dublin Ireland";
28 airports["LHR"] = "London Heathrow";
29
30 std::cout << "All the airports:" << std::endl;
31 for (auto const &pair : airports) {
32 std::cout << "The airport code is " << pair.first << " for " << pair.second << std::endl;
33 }
34 std::cout << " " << std::endl;
35
36 std::cout << "Type in an airport code: ";
37 std::cin >> airportName;
38 std::cout << " " << std::endl;
39
40 if (airports.count(airportName) > 0) {
41 std::cout << "The name of the airport you chose is " << airports[airportName];
42 } else {
43 std::cout << "That airport is not in the airport's dictionary.";
44 }
45
46 std::cout << " " << std::endl;
47
48 std::cout << "\nDone." << std::endl;
49 return 0;
50}
1/* Created by: Mr. Coxall
2 * Created on: Sep 2020
3 * This program uses a dictionary
4*/
5
6using System;
7using System.Collections.Generic;
8
9/*
10 * The Program class
11*/
12class Program {
13 static void Main() {
14 // this function uses a dictionary
15 string airportName;
16
17 // an empty dictionary
18 Dictionary<string, string> airports = new Dictionary<string, string>();
19
20 // a dictionary filled with data
21 Dictionary<char, int> someInfo = new Dictionary<char, int>() {
22 {'a', 1},
23 {'b', 2},
24 {'c', 3}
25 };
26
27 // adding items
28 airports["YYZ"] = "Toronto Pearson";
29 airports["YOW"] = "Ottawa Canada";
30 airports["DUB"] = "Dublin Ireland";
31 airports["LHR"] = "London Heathrow";
32
33 Console.WriteLine("All the airports:");
34 foreach (var pair in airports) {
35 Console.WriteLine("The airport code is " + pair.Key + " for " + pair.Value);
36 }
37 Console.WriteLine();
38
39 Console.Write("Type in an airport code: ");
40 airportName = Console.ReadLine();
41 Console.WriteLine();
42
43 if (airports.ContainsKey(airportName)) {
44 Console.WriteLine("The name of the airport you chose is " + airports[airportName]);
45 } else {
46 Console.WriteLine("That airport is not in the airport's dictionary.");
47 }
48
49 Console.WriteLine("\nDone.");
50 }
51}
1/**
2 * Created by: Mr. Coxall
3 * Created on: Sep 2020
4 * This program uses a map
5 */
6
7package main
8
9import (
10 "fmt"
11)
12
13func main() {
14 // this function uses a map
15
16 var airportName string
17
18 // an empty map
19 airports := make(map[string]string)
20
21 /*
22 // a map filled with data
23 someInfo := map[byte]int{
24 'a': 1,
25 'b': 2,
26 'c': 3,
27 }
28 */
29
30 // adding items
31 airports["YYZ"] = "Toronto Pearson"
32 airports["YOW"] = "Ottawa Canada"
33 airports["DUB"] = "Dublin Ireland"
34 airports["LHR"] = "London Heathrow"
35
36 fmt.Println("All the airports:")
37 for code, name := range airports {
38 fmt.Printf("The airport code is %s for %s\n", code, name)
39 }
40 fmt.Println()
41
42 fmt.Print("Type in an airport code: ")
43 fmt.Scanln(&airportName)
44 fmt.Println()
45
46 if name, ok := airports[airportName]; ok {
47 fmt.Println("The name of the airport you chose is", name)
48 } else {
49 fmt.Println("That airport is not in the airport's dictionary.")
50 }
51
52 fmt.Println("\nDone.")
53}
1/*
2 * This program uses a map
3 *
4 * @author Mr Coxall
5 * @version 1.0
6 * @since 2020-09-01
7 */
8
9import java.util.Scanner;
10import java.util.HashMap;
11import java.util.Map;
12
13public class Main {
14 public static void main(String[] args) {
15 // this function uses a uses a map
16 String airportName;
17
18 // an empty map
19 Map<String, String> airports = new HashMap<>();
20
21 // a map filled with data
22 Map<Character, Integer> someInfo = new HashMap<>();
23 someInfo.put('a', 1);
24 someInfo.put('b', 2);
25 someInfo.put('c', 3);
26
27 // adding items
28 airports.put("YYZ", "Toronto Pearson");
29 airports.put("YOW", "Ottawa Canada");
30 airports.put("DUB", "Dublin Ireland");
31 airports.put("LHR", "London Heathrow");
32
33 System.out.println("All the airports:");
34 for (Map.Entry<String, String> entry : airports.entrySet()) {
35 System.out.println("The airport code is " + entry.getKey() + " for " + entry.getValue());
36 }
37 System.out.println();
38
39 Scanner scanner = new Scanner(System.in);
40 System.out.print("Type in an airport code: ");
41 airportName = scanner.nextLine();
42 System.out.println();
43
44 if (airports.containsKey(airportName)) {
45 System.out.println("The name of the airport you chose is " + airports.get(airportName));
46 } else {
47 System.out.println("That airport is not in the airport's dictionary.");
48 }
49
50 // close the Scanner object
51 scanner.close();
52 System.out.println("\nDone.");
53 }
54}
1/* Created by: Mr. Coxall
2 * Created on: Sep 2020
3 * This program uses a map
4 */
5
6const prompt = require("prompt-sync")()
7
8// this function uses a map
9let airportName;
10
11// an empty map
12const airports = new Map();
13
14// a map filled with data
15const someInfo = new Map([
16 ['a', 1],
17 ['b', 2],
18 ['c', 3],
19]);
20
21// adding items
22airports.set("YYZ", "Toronto Pearson");
23airports.set("YOW", "Ottawa Canada");
24airports.set("DUB", "Dublin Ireland");
25airports.set("LHR", "London Heathrow");
26
27console.log("All the airports:");
28for (let [code, name] of airports) {
29 console.log(`The airport code is ${code} for ${name}`);
30}
31console.log();
32
33airportName = prompt("Type in an airport code: ");
34console.log();
35
36if (airports.has(airportName)) {
37 console.log("The name of the airport you chose is", airports.get(airportName));
38} else {
39 console.log("That airport is not in the airport's dictionary.");
40}
41
42console.log("\nDone.")
1#!/usr/bin/env python3
2"""
3Created by: Mr. Coxall
4Created on: Sep 2020
5This module uses an associative array
6"""
7
8
9def main() -> None:
10 """The main() this function uses an associative array, returns None."""
11
12 airports = {}
13 some_info = {'item1': 1,
14 'item2': 2,
15 }
16
17 # adding items
18 airports['YYZ'] = "Toronto Pearson"
19 airports['YOW'] = "Ottawa Canada"
20 airports['DUB'] = "Dublin Ireland"
21 airports['LHR'] = "London Heathrow"
22
23 # input & process
24 print("All the airports:")
25 for key, value in airports.items():
26 print(f"The airport code is {key} for {value}.")
27 print("")
28
29 airport_name = input("Type in an airport code: ")
30 if airport_name in airports:
31 print(f"The name of the airport you chose is {airports[airport_name]}.")
32 else:
33 print("That airport is not in the airport's dictionary.")
34
35 print("\nDone.")
36
37
38if __name__ == "__main__":
39 main()
Example Output
