Safekipedia

Associative array

Adventurer · ages 7–10Adapted from Wikipedia
A graph showing how the average number of cache misses grows as a hash table fills up, with different collision resolution methods compared.

In computer science, an associative array is a way of storing information as pairs of a key and a value. It can also be called a key-value store, a map, a symbol table, or a dictionary. Each key appears only once in the collection, so each key points to one value. In math, an associative array is a function with a limited set of inputs. People can look up values, remove them, or add new ones.

The dictionary problem is a well-known challenge in building data structures that can work as associative arrays. The two main solutions are hash tables and search trees. Sometimes the problem can also be solved using arrays, binary search trees, or other special structures.

Many programming languages include associative arrays as primitive data types. Many other languages use software libraries to support them. Content-addressable memory is a type of computer hardware that directly supports associative arrays.

Associative arrays have many uses, including helpful programming patterns such as memoization and the decorator pattern. The name does not come from the associative property in mathematics. It comes from the way values are linked with keys. It should not be confused with associative processors.

Operations

In an associative array, the link between a key and a value is often called a "mapping." The same word can also mean the act of making a new link. There are three common operations. Insert (or put) adds a new key and value pair, and it replaces any older value for that key. Remove (or delete) takes a key and its value out. Lookup (or find or get) finds the value linked to a key. If no value is found, some systems cause an exception, while others give back a default value, such as zero, null, or a value chosen in advance.

Other operations can count the mappings or use an iterator to go through all of them. The order of the results is usually decided by how the system is built. A multimap lets one key have several values. A bidirectional map lets you look up a key from a value, as well as a value from a key. For example, in a library, books can be the keys and patrons the values. This shows which person has borrowed which book. The notation used in Python or JSON can show this kind of data.

Implementation

For dictionaries with very few mappings, an association list can be used. It is a linked list of mappings. It is easy to build, but it gets slower as the number of mappings grows. When keys fall within a small range, direct addressing stores each value in an array cell for its key. This is simple and fast, but it needs space for every key in the range, so it only works well when that range is small. The two major approaches are a hash table and a search tree.

A hash table is the most common general-purpose choice. It uses a hash function to sort each key into a "bucket" in an array, and it is usually quick. When two keys end up in the same bucket, called a collision, the table handles it with separate chaining or open addressing. Search trees, such as an AVL tree or a red–black tree, have a better worst case and keep their items in order. This helps when finding all values between two limits. Hash tables are usually faster on average, though.

This graph compares the average number of CPU cache misses required to look up elements in large hash tables (far exceeding size of the cache) with chaining and linear probing. Linear probing performs better due to better locality of reference, though as the table gets full, its performance degrades drastically.

Main article: Hash table

Main article: Search tree

Underlying data structureLookup or RemovalInsertionOrdered
averageworst caseaverageworst case
Hash tableO(1)O(n)O(1)O(n)No
Self-balancing binary search treeO(log n)O(log n)O(log n)O(log n)Yes
unbalanced binary search treeO(log n)O(n)O(log n)O(n)Yes
Sequential container of key–value pairs
(e.g. association list)
O(n)O(n)O(1)O(1)No

Ordered dictionary

A dictionary does not need any order. To keep items in a set order, programmers often use special versions of the associative array. There are two kinds. In one kind, the order comes from sorting the keys, as in the tree map container in C++. In the other kind, the order depends on the order in which items were added. This is true for the "ordered dictionary" in .NET Framework, and the LinkedHashMap in Java and Python.

The second kind is more common. Ordered dictionaries can be built using an association list, by placing a doubly linked list on top of a normal dictionary, or by moving the data into a dense array that keeps items in the order they were added.

Language support

Main article: Comparison of programming languages (associative array)

Associative arrays can be added to almost any programming language. Many language systems include them in their standard tools. Some languages have special syntax for them that looks like array subscripts. The first built-in support appeared in 1969 in SNOBOL4, where they were called "table". TMG had tables with string keys and integer values. MUMPS used multi-dimensional associative arrays as its main data structure. SETL used them as one way to build sets and maps. Many modern scripting languages support associative arrays as a main container type. These include AWK, Rexx, Perl, PHP, Tcl, JavaScript, Maple, Python, Ruby, Wolfram Language, Go, and Lua. Many other languages offer them as library functions without special syntax.

Languages use different names for them. In Smalltalk, Objective-C, .NET, Python, REALbasic, Swift, VBA and Delphi, they are called dictionaries. In Perl and Ruby, they are called hashes. In C++, C#, Java, Go, Clojure, Scala, OCaml, and Haskell, they are called maps (see map (C++), unordered_map (C++), and Map). In Common Lisp and Windows PowerShell, they are called hash tables. In Maple and Lua, they are called tables. In PHP and R, all arrays can be associative, but keys must be integers or strings. In JavaScript (see also JSON), all objects work as associative arrays with string keys. The Map and WeakMap types accept any objects as keys. In Lua, they are the basic building block for all data structures. In Visual FoxPro, they are called Collections. The D language also supports associative arrays.

Permanent storage

Main article: Key–value store

Many programs that use associative arrays need to save their data for longer. They often save it in a computer file. A common method is called archiving or serialization. It changes the objects into text or binary form so they can be written straight to a file. The object model that the program uses, such as .Net or Cocoa, often has built-in tools that turn the data into text.

Programs that handle very large amounts of data cannot save everything in separate files easily. They need a database management system (DB). Some DB systems save associative arrays together with their key. This way, each array can be loaded or saved using its key. These key–value stores have been around for many years, nearly as long as the more common relational database (RDBs). However, they were only useful for certain special jobs. RDBs handled most of the work. Saving objects in an RDB can be tricky, which is a problem called object-relational impedance mismatch. After about 2010, people needed fast databases for cloud computing. This brought key–value stores back. They can store and get associative arrays directly, which makes common web tasks much faster.

Quiz time!

4 questions about Associative array

Question 1 of 4

What does an associative array store information as?

Keep exploring

This article is a child-friendly adaptation of the Wikipedia article on Associative array, available under CC BY-SA 4.0.

Images from Wikimedia Commons. Tap any image to view credits and license.