Often in programming it’s useful to be able to access one piece of information based on other piece of information. For example, if you wanted to be able to populate city and state given a zip code, you’d want to be able to provide the zip code and lookup that city and state. Now you could just have a list of city, state and zip codes like this:

[{city: Powder Springs, state: GA, zipCode: 30127},
{city: Atlanta, state: GA, zipCode: 30324},

But if you store the data this way, you would need to look at every single entry in order to see if that entry was the one with the zip code you wanted. This could get very expensive (time, processor), not to mention annoying to program.

To help us out, most languages have a “Map”, “Dictionary” or “Hash” data structure in the standard libraries that help with this situation. Instead of having a list of the data, we add data to this Map in key-value pairs. The key is what we use to lookup the value. In our example, zip code is our key and an object with city and state is our value. Our city, state and zip code data would look like this:

30127 -> [Powder Springs, GA]
30324 -> [Atlanta, GA]

The computer will now store that information in a way that when you ask for “30324”, it can immediately go to that entry and grab “Atlanta, GA”.

Can you think of situations where this type of data structure would be useful?

Here are some basic code examples in different languages:


const m = new Map([
      [30127, {city: "Powder Springs", state: "GA"}], 
      [30324, {city: "Atlanta", state: "GA"}]
m.set(30026, {city: "Duluth", state: "GA"});
const cityInfo = m.get(30127); 


var cityLookup = new Dictionary {
     {"30127", ("Powder Springs", "GA")},
     {"30324", ("Atlanta", "GA")}
cityLookup.Add("30026", ("Duluth", "GA"));
var city = cityLookup["30127"];
Share This