Language support
The following is a comparison ofAWK
AWK has built-in, language-level support for associative arrays. For example:C
There is no standard implementation of associative arrays in C, but a 3rd-party library, C Hash Table, with BSD license, is available. Another 3rd-party library, uthash, also creates associative arrays from C structures. A structure represents a value, and one of the structure fields serves as the key. Finally, theC#
C# uses the collection classes provided by the .NET Framework. The most commonly used associative array type isSystem.Collections.Generic.Dictionary
, which is implemented as a mutable hash table. The relatively new System.Collections.Immutable
package, available in .NET Framework versions 4.5 and above, and in all versions of .NET Core, also includes the System.Collections.Immutable.Dictionary
type, which is implemented using an Creation
The following demonstrates three means of populating a mutable dictionary: * theAdd
method, which adds a key and value and throws an exception if the key already exists in the dictionary;
* assigning to the indexer, which overwrites any existing value, if present; and
* assigning to the backing property of the indexer, for which the indexer is Add
.
Access by key
Values are primarily retrieved using the indexer (which throws an exception if the key does not exist) and theTryGetValue
method, which has an output parameter for the sought value and a Boolean return-value indicating whether the key was found.
sallyNumber
value will now contain the string "555-9999"
.
Enumeration
A dictionary can be viewed as a sequence of keys, sequence of values, or sequence of pairs of keys and values represented by instances of theKeyValuePair
type, although there is no guarantee of order. For a sorted dictionary, the programmer could choose to use a SortedDictionary
or use the .Sort
C++
C++ has a form of associative array calledstd::map
(see Standard Template Library#Containers). One could create a phone-book map with the following code in C++:
std::string
values:
std::map
class is templated which allows the map
instances. For a given instance of the map
class the keys must be of the same base type. The same must be true for all of the values. Although std::map
is typically implemented using a std::unordered_map
, which has the algorithmic characteristics of a hash table. This is a common vendor extension to the hash_map
, available from such implementations as SGI and STLPort.
Cobra
Initializing an empty dictionary and adding items inColdFusion Markup Language
A structure inD
D offers direct support for associative arrays in the core language; such arrays are implemented as a chaining hash table with binary trees. The equivalent example would be:Delphi
Erlang
Erlang offers many ways to represent mappings; three of the most common in the standard library are keylists, dictionaries, and maps.Keylists
Keylists are lists oflists
module.
lists:keyfind/3
function:
Dictionaries
Dictionaries are implemented in thedict
module of the standard library. A new dictionary is created using the dict:new/0
function and new key/value pairs are stored using the dict:store/3
function:
dict:find/2
function:
orddict
module, implementing ordered dictionaries, and gb_trees
, implementing general balanced trees.
Maps
Maps were introduced in OTP 17.0, and combine the strengths of keylists and dictionaries. A map is defined using the syntax#
:
maps
module. For example, the maps:find/2
function returns the value associated with a key:
F#
Map<'Key,'Value>
At runtime, F# provides theCollections.Map<'Key,'Value>
type, which is an immutable =Creation
= The following example calls theMap
constructor, which operates on a list (a semicolon delimited sequence of elements enclosed in square brackets) of tuples (which in F# are comma-delimited sequences of elements).
=Access by key
= Values can be looked up via one of theMap
members, such as its indexer or Item
property (which throw an exception if the key does not exist) or the TryFind
function, which returns an Some
, for a successful lookup, or None
, for an unsuccessful one. sallyNumber
value would contain the string "555-9999"
.
Dictionary<'TKey,'TValue>
Because F# is a .NET language, it also has access to features of the .NET Framework, including the type (which is implemented as a=Creation
= Thedict
function provides a means of conveniently creating a .NET dictionary that is not intended to be mutated; it accepts a sequence of tuples and returns an immutable object that implements IDictionary<'TKey,'TValue>
.
=Access by key
=IDictionary
instances have an indexer that is used in the same way as Map
, although the equivalent to TryFind
is TryGetValue
, which has an output parameter for the sought value and a Boolean return value indicating whether the key was found.
Enumeration
A dictionary or map can be enumerated usingSeq.map
.
FoxPro
Go
Go has built-in, language-level support for associative arrays, called "maps". A map's key type may only be a boolean, numeric, string, array, struct, pointer, interface, or channel type. A map type is written:map eytypealuetype
Adding elements one at a time:
Haskell
TheJava
InphoneBook.get("Sally Smart")
is "555-9999"
. This code uses a hash map to store the associative array, by calling the constructor of the class. However, since the code only uses methods common to the interface , a self-balancing binary tree could be used by calling the constructor of the class (which implements the subinterface ), without changing the definition of the phoneBook
variable, or the rest of the code, or using other underlying data structures that implement the Map
interface.
The hash function in Java, used by HashMap and HashSet, is provided by the method. Since every class in Java inherits from , every object has a hash function. A class can override the default implementation of hashCode()
to provide a custom hash function more in accordance with the properties of the object.
The Object
class also contains the method, which tests an object for equality with another object. Hashed data structures in Java rely on objects maintaining the following contract between their hashCode()
and equals()
methods:
For two objects ''a'' and ''b'',
equals()
must also override hashCode()
, and vice versa, so that hashCode()
is based on the same properties (or a subset of the properties) as equals()
.
A further contract that a hashed data structure has with the object is that the results of the hashCode()
and equals()
methods will not change once the object has been inserted into the map. For this reason, it is generally a good practice to base the hash function on JavaScript
Map and WeakMap
Modern JavaScript handles associative arrays, using theMap
and WeakMap
classes. A map does not contain any keys by default; it only contains what is explicitly put into it. The keys and values can be any type (including functions, objects, or any primitive).
=Creation
= A map can be initialized with all items during construction:=Access by key
= Accessing an element of the map can be done with theget
method:
sallyNumber
will now contain the string "555-9999".
=Enumeration
= The keys in a map are ordered. Thus, when iterating through it, a map object returns keys in order of insertion. The following demonstrates enumeration using a for-loop:Object
An object is similar to a map—both let you set keys to values, retrieve those values, delete keys, and detect whether a value is stored at a key. For this reason (and because there were no built-in alternatives), objects historically have been used as maps. However, there are important differences that make a map preferable in certain cases. In JavaScript an object is a mapping from property names to values—that is, an associative array with one caveat: the keys of an object must be either a string or a symbol (native objects and primitives implicitly converted to a string keys are allowed). Objects also include one feature unrelated to associative arrays: an object has a prototype, so it contains default keys that could conflict with user-defined keys. So, doing a lookup for a property will point the lookup to the prototype's definition if the object does not define the property. An object literal is written as
. For example:
Object.setPrototypeOf
function:
Object.create(null)
:
Map
/WeakMap
classes are best for this purpose. The reasoning behind this is that if Array is extended via prototype and Object is kept pristine, for and for-in loops will work as expected on associative 'arrays'. This issue has been brought to the fore by the popularity of JavaScript frameworks that make heavy and sometimes indiscriminate use of prototypes to extend JavaScript's inbuilt types.
SeJulia
InKornShell 93, and compliant shells
InLisp
Lisp programming language">Lisp Lisp (historically LISP, an abbreviation of "list processing") is a family of programming languages with a long history and a distinctive, fully parenthesized Polish notation#Explanation, prefix notation. Originally specified in the late 1950s, ...(x . y)
is used to indicate a cons
ed pair. Keys and values need not be the same type within an alist. Lisp and Scheme provide operators such as assoc
to manipulate alists in ways similar to associative arrays.
A set of operations specific to the handling of association lists exists for acons
function is employed, creating and returning a new association list. An association list in Common Lisp mimicks a stack, that is, adheres to the last-in-first-out (LIFO) principle, and hence prepends to the list head.
cons
operations.
push
operation also allows inserting entries into an association list, an entry having to constitute a key-value cons in order to retain the mapping's validity.
assoc
, which might be configured for the test predicate and direction, especially searching the association list from its end to its front. The result, if positive, returns the entire entry cons, not only its value. Failure to obtain a matching key leads to a return of the NIL
value.
assoc
exist: assoc-if
expects a predicate function that tests each entry's key, returning the first entry for which the predicate produces a non-NIL
value upon invocation. assoc-if-not
inverts the logic, accepting the same arguments, but returning the first entry generating NIL
.
rassoc
.
rassoc-if
and rassoc-if-not
exist.
find
, find-if
, find-if-not
, as well as pertinent functions like position
and its derivates.
make-hash-table
function, whose arguments encompass, among other configurations, a predicate to test the entry key. While tolerating arbitrary objects, even heterogeneity within a single hash table instance, the specification of this key :test
function is confined to distinguishable entities: the Common Lisp standard only mandates the support of eq
, eql
, equal
, and equalp
, yet designating additional or custom operations as permissive for concrete implementations.
gethash
function permits obtaining the value associated with a key.
gethash
actually returns two values: the value or substitute value for the key and a boolean indicator, returning T
if the hash table contains the key and NIL
to signal its absence.
remhash
for deleting the entry associated with a key.
clrhash
completely empties the hash table.
maphash
function specializes in iterating hash tables.
loop
construct makes provisions for iterations, through keys, values, or conjunctions of both.
with-hash-table-iterator
, an iterator-creating macro, the processing of which is intended to be driven by the caller.
LPC
LPC implements associative arrays as a fundamental type known as either "map" or "mapping", depending on the driver. The keys and values can be of any type. A mapping literal is written as( key_1 : value_1, key_2 : value_2
. Procedural code looks like:
if(member(phone_book, "John Smith")) write("John Smith is listed.\n");
Deletion is accomplished using a function called either m_delete() or map_delete(), depending on the driver: m_delete(phone_book, "Sally Smart");
LPC drivers of the Amylaar family implement multivalued mappings using a secondary, numeric index (other drivers of the Lua
In Lua, "table" is a fundamental type that can be used either as an array (numerical index, fast) or as an associative array. The keys and values can be of any type, except nil. The following focuses on non-numerical indexes. A table literal is written as
. For example:
Mathematica and Wolfram Language
MUMPS
In MUMPS every array is an associative array. The built-in, language-level, direct support for associative arrays applies to private, process-specific arrays stored in memory called "locals" as well as to the permanent, shared, global arrays stored on disk which are available concurrently to multiple jobs. The name for globals is preceded by the circumflex "^" to distinguish them from local variables. SET ^phonebook("Sally Smart")="555-9999" ;; storing permanent data SET phonebook("John Doe")="555-1212" ;; storing temporary data SET phonebook("J. Random Hacker")="553-1337" ;; storing temporary data MERGE ^phonebook=phonebook ;; copying temporary data into permanent data Accessing the value of an element simply requires using the name with the subscript: WRITE "Phone Number :",^phonebook("Sally Smart"),! You can also loop through an associated array as follows: SET NAME="" FOR S NAME=$ORDER(^phonebook(NAME)) QUIT:NAME="" WRITE NAME," Phone Number :",^phonebook(NAME),!Objective-C (Cocoa/GNUstep)
Cocoa andNSMutableDictionary
(a mutable version of NSDictionary
) class cluster. This class allows assignments between any two objects. A copy of the key object is made before it is inserted into NSMutableDictionary
, therefore the keys must conform to the NSCopying
protocol. When being inserted to a dictionary, the value object receives a retain message to increase its reference count. The value object will receive the release message when it will be deleted from the dictionary (either explicitly or by adding to the dictionary a different object with the same key).
NSEnumerator
:
NSFastEnumeration
construct:
NSDictionary
(NSMutableDictionary
). This can be illustrated with this compact example:
OCaml
TheHashtbl.hash
, which is defined automatically for all types. To use a modified hash function, use the functor interface Hashtbl.Make
to create a module, such as with Map
.
Finally, functional maps (represented as immutable balanced binary trees):
Map
, you have to provide the functor Map.Make
with a module which defines the key type and the comparison function. The third-party library ExtLib provides a polymorphic version of functional maps, called PMap
, which is given a comparison function upon creation.
Lists of pairs and functional maps both provide a purely functional interface. By contrast, hash tables provide an imperative interface. For many operations, hash tables are significantly faster than lists of pairs and functional maps.
OptimJ
ThePerl 5
%
=>
token, which is semantically mostly identical to the comma and makes the key-value association clearer:
$hash_name
– the key is surrounded by $
, indicating that the hash element itself is a scalar value, even though it is part of a hash. The value of $phone_book
is '555-1212'
. The %
sigil is only used when referring to the hash as a whole, such as when asking for keys %phone_book
.
The list of keys and values can be extracted using the built-in functions keys
and values
, respectively. So, for example, to print all the keys of a hash:
each
function:
keys
function, the syntax is as follows:
Perl 6 (Raku)
Perl 6, renamed as "Raku", also has built-in, language-level support for associative arrays, which are referred to as ''hashes'' or as objects performing the "associative" role. As in Perl 5, Perl 6 default hashes are flat: keys are strings and values are scalars. One can define a hash to not coerce all keys to strings automatically: these are referred to as "object hashes", because the keys of such hashes remain the original object rather than a stringification thereof. A hash variable is typically marked by a%
=>
token, which makes the key-value association clearer:
%hash_name
– the key is surrounded by curly braces and the hash name (note that the sigil does not change, contrary to Perl 5). The value of %phone-book
is '555-1212'
.
The list of keys and values can be extracted using the built-in functions keys
and values
, respectively. So, for example, to print all the keys of a hash:
kv
method:
PHP
SplObjectStorage
class from the Standard PHP Library (SPL).
Pike
Pike has built-in support for associative arrays, which are referred to as mappings. Mappings are created as follows:phonebook Sally Smart"/code> would return the string "555-9999"
, and phonebook John Smith"/code> would return 0.
Iterating through a mapping can be done using foreach
:
foreach(phonebook; string key; string value)
Or using an iterator object:
Mapping.Iterator i = get_iterator(phonebook);
while (i->index())
Elements of a mapping can be removed using m_delete
, which returns the value of the removed index:
string sallys_number = m_delete(phonebook, "Sally Smart");
PostScript
In PostScript
PostScript (PS) is a page description language and dynamically typed, stack-based programming language. It is most commonly used in the electronic publishing and desktop publishing realm, but as a Turing complete programming language, it c ...
, associative arrays are called dictionaries. In Level 1 PostScript they must be created explicitly, but Level 2 introduced direct declaration using a double-angled-bracket syntax:
% Level 1 declaration
3 dict dup begin
/red (rouge) def
/green (vert) def
/blue (bleu) def
end
% Level 2 declaration
<<
/red (rot)
/green (gruen)
/blue (blau)
>>
% Both methods leave the dictionary on the operand stack
Dictionaries can be accessed directly, using get
, or implicitly, by placing the dictionary on the dictionary stack using begin
:
% With the previous two dictionaries still on the operand stack
/red get print % outputs 'rot'
begin
green print % outputs 'vert'
end
Dictionary contents can be iterated through using forall
, though not in any particular order:
% Level 2 example
<<
/This 1
/That 2
/Other 3
>> forall
Which may output:
That is 2
This is 1
Other is 3
Dictionaries can be augmented (up to their defined size only in Level 1) or altered using put
, and entries can be removed using undef
:
% define a dictionary for easy reuse:
/MyDict <<
/rouge (red)
/vert (gruen)
>> def
% add to it
MyDict /bleu (blue) put
% change it
MyDict /vert (green) put
% remove something
MyDict /rouge undef
Prolog
Some versions of Prolog
Prolog is a logic programming language that has its origins in artificial intelligence, automated theorem proving, and computational linguistics.
Prolog has its roots in first-order logic, a formal logic. Unlike many other programming language ...
include dictionary ("dict") utilities.
Python
In Python
Python may refer to:
Snakes
* Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia
** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia
* Python (mythology), a mythical serpent
Computing
* Python (prog ...
, associative arrays are called "dictionaries
A dictionary is a listing of lexemes from the lexicon of one or more specific languages, often arranged Alphabetical order, alphabetically (or by Semitic root, consonantal root for Semitic languages or radical-and-stroke sorting, radical an ...
". Dictionary literals are delimited by curly braces:
phonebook =
Dictionary items can be accessed using the array indexing operator:
>>> phonebook Sally Smart"'555-9999'
Loop iterating through all the keys of the dictionary:
>>> for key in phonebook:
... print(key, phonebook ey
Sally Smart 555-9999
J. Random Hacker 553-1337
John Doe 555-1212
Iterating through (key, value) tuples:
>>> for key, value in phonebook.items():
... print(key, value)
Sally Smart 555-9999
J. Random Hacker 553-1337
John Doe 555-1212
Dictionary keys can be individually deleted using the del
statement. The corresponding value can be returned before the key-value pair is deleted using the "pop" method of "dict" type:
>>> del phonebook John Doe">>> val = phonebook.pop("Sally Smart")
>>> phonebook.keys() # Only one key left
J. Random Hacker'
Python 2.7 and 3.x also suppor
dict comprehensions
(similar to list comprehension
A list comprehension is a syntactic construct available in some programming languages for creating a list based on existing lists. It follows the form of the mathematical '' set-builder notation'' (''set comprehension'') as distinct from the use o ...
s), a compact syntax for generating a dictionary from any iterator:
>>> square_dict =
>>> square_dict
>>>
Strictly speaking, a dictionary is a super-set of an associative array, since neither the keys or values are limited to a single datatype. One could think of a dictionary as an "associative list" using the nomenclature of Python. For example, the following is also legitimate:
phonebook =
The dictionary keys must be of an immutable
In object-oriented (OO) and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created.Goetz et al. ''Java Concurrency in Practice''. Addison Wesley Professional, 2006, Secti ...
data type. In Python, strings are immutable due to their method of implementation.
Red
In Red
Red is the color at the long wavelength end of the visible spectrum of light, next to orange and opposite violet. It has a dominant wavelength of approximately 625–750 nanometres. It is a primary color in the RGB color model and a seconda ...
the built-in map!
datatype provides an associative array that maps values of word, string, and scalar key types to values of any type. A hash table is used internally for lookup.
A map can be written as a literal, such as #(key1 value1 key2 value2 ...)
, or can be created using make map! ey1 value1 key2 value2 .../code>:
Red itle:"My map"
my-map: make map! "Sally Smart" "555-9999"
"John Doe" "555-1212"
"J. Random Hacker" "553-1337"
; Red preserves case for both keys and values, however lookups are case insensitive by default; it is possible to force case sensitivity using the /case
refinement for select
and put
.
; It is of course possible to use word!
values as keys, in which case it is generally preferred to use set-word!
values when creating the map, but any word type can be used for lookup or creation.
my-other-map: make map! oo: 42 bar: false
; Notice that the block is not reduced or evaluated in any way, therefore in the above example the key bar
is associated with the word!
false
rather than the logic!
value false; literal syntax can be used if the latter is desired:
my-other-map: make map! oo: 42 bar: #[false
; or keys can be added after creation:
my-other-map: make map! [foo: 42">alse">oo: 42 bar: #[false
; or keys can be added after creation:
my-other-map: make map! [foo: 42my-other-map/bar: false
; Lookup can be written using path!
notation or using the select
action:
select my-map "Sally Smart"
my-other-map/foo
; You can also loop through all keys and values with foreach
:
foreach [key value] my-map [
print [key "is associated to" value]
]
; A key can be removed using remove/key
:
remove/key my-map "Sally Smart"
REXX
In REXX, associative arrays are called "stem variables" or "Compound variables".
KEY = 'Sally Smart'
PHONEBOOK.KEY = '555-9999'
KEY = 'John Doe'
PHONEBOOK.KEY = '555-1212'
KEY = 'J. Random Hacker'
PHONEBOOK.KEY = '553-1337'
Stem variables with numeric keys typically start at 1 and go up from there. The 0-key stem variable
by convention contains the total number of items in the stem:
NAME.1 = 'Sally Smart'
NAME.2 = 'John Doe'
NAME.3 = 'J. Random Hacker'
NAME.0 = 3
REXX has no easy way of automatically accessing the keys of a stem variable; and typically the
keys are stored in a separate associative array, with numeric keys.
Ruby
In Ruby
Ruby is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapph ...
a hash table is used as follows:
phonebook =
phonebook John Doe'
Ruby supports hash looping and iteration with the following syntax:
irb(main):007:0> ### iterate over keys and values
irb(main):008:0* phonebook.each
Sally Smart => 555-9999
John Doe => 555-1212
J. Random Hacker => 553-1337
=>
irb(main):009:0> ### iterate keys only
irb(main):010:0* phonebook.each_key
Sally Smart
John Doe
J. Random Hacker
=>
irb(main):011:0> ### iterate values only
irb(main):012:0* phonebook.each_value
555-9999
555-1212
553-1337
=>
Ruby also supports many other useful operations on hashes, such as merging hashes, selecting or rejecting elements that meet some criteria, inverting (swapping the keys and values), and flattening a hash into an array.
Rust
The Rust
Rust is an iron oxide, a usually reddish-brown oxide formed by the reaction of iron and oxygen in the catalytic presence of water or air moisture. Rust consists of hydrous iron(III) oxides (Fe2O3·nH2O) and iron(III) oxide-hydroxide (FeO(OH) ...
standard library provides a hash map (std::collections::HashMap
) and a B-tree
In computer science, a B-tree is a self-balancing tree data structure that maintains sorted data and allows searches, sequential access, insertions, and deletions in logarithmic time. The B-tree generalizes the binary search tree, allowing fo ...
map (std::collections::BTreeMap
). They share several methods with the same names, but have different requirements for the types of keys that can be inserted. The HashMap
requires keys to implement the Eq
(equivalence relation
In mathematics, an equivalence relation is a binary relation that is reflexive, symmetric, and transitive. The equipollence relation between line segments in geometry is a common example of an equivalence relation. A simpler example is equ ...
) and Hash
(hashability) traits and it stores entries in an unspecified order, and the BTreeMap
requires the Ord
(total order
In mathematics, a total order or linear order is a partial order in which any two elements are comparable. That is, a total order is a binary relation \leq on some set X, which satisfies the following for all a, b and c in X:
# a \leq a ( re ...
) trait for its keys and it stores entries in an order defined by the key type. The order is reflected by the default iterators.
use std::collections::HashMap;
let mut phone_book = HashMap::new();
phone_book.insert("Sally Smart", "555-9999");
phone_book.insert("John Doe", "555-1212");
phone_book.insert("J. Random Hacker", "555-1337");
The default iterators visit all entries as tuples. The HashMap
iterators visit entries in an unspecified order and the BTreeMap
iterator visits entries in the order defined by the key type.
for (name, number) in &phone_book
There is also an iterator for keys:
for name in phone_book.keys()
S-Lang
S-Lang
The S-Lang programming library is a software library for Unix, Windows, VMS, OS/2, and Mac OS X. It provides routines for embedding an interpreter for the S-Lang scripting language, and components to facilitate the creation of text-based applica ...
has an associative array type:
phonebook = Assoc_Type[];
phonebook Sally Smart"= "555-9999"
phonebook John Doe"= "555-1212"
phonebook J. Random Hacker"= "555-1337"
You can also loop through an associated array in a number of ways:
foreach name (phonebook)
To print a sorted-list, it is better to take advantage of S-lang's strong
support for standard arrays:
keys = assoc_get_keys(phonebook);
i = array_sort(keys);
vals = assoc_get_values(phonebook);
array_map (Void_Type, &vmessage, "%s %s", keys vals ;
Scala
Scala provides an immutable Map
class as part of the scala.collection
framework:
val phonebook = Map("Sally Smart" -> "555-9999",
"John Doe" -> "555-1212",
"J. Random Hacker" -> "553-1337")
Scala's type inference
Type inference, sometimes called type reconstruction, refers to the automatic detection of the type of an expression in a formal language. These include programming languages and mathematical type systems, but also natural languages in some bran ...
will decide that this is a Map tring, String/code>. To access the array:
phonebook.get("Sally Smart")
This returns an Option
type, Scala's equivalent of the Maybe monad in Haskell.
Smalltalk
In Smalltalk
Smalltalk is a purely object oriented programming language (OOP) that was originally created in the 1970s for educational use, specifically for constructionist learning, but later found use in business. It was created at Xerox PARC by Learni ...
a Dictionary
is used:
phonebook := Dictionary new.
phonebook at: 'Sally Smart' put: '555-9999'.
phonebook at: 'John Doe' put: '555-1212'.
phonebook at: 'J. Random Hacker' put: '553-1337'.
To access an entry the message #at:
is sent to the dictionary object:
phonebook at: 'Sally Smart'
Which gives:
'555-9999'
A dictionary hashes, or compares, based on equality and marks both key and value as
strong references. Variants exist in which hash/compare on identity (IdentityDictionary) or keep weak references (WeakKeyDictionary / WeakValueDictionary).
Because every object implements #hash, any object can be used as key (and of course also as value).
SNOBOL
SNOBOL
SNOBOL ("StriNg Oriented and symBOlic Language") is a series of programming languages developed between 1962 and 1967 at AT&T Bell Laboratories by David J. Farber, Ralph Griswold and Ivan P. Polonsky, culminating in SNOBOL4. It was one of a ...
is one of the first (if not the first) programming languages to use associative arrays. Associative arrays in SNOBOL are called Tables.
PHONEBOOK = TABLE()
PHONEBOOK Sally Smart'= '555-9999'
PHONEBOOK John Doe'= '555-1212'
PHONEBOOK J. Random Hacker'= '553-1337'
Standard ML
The SML'97 standard of the Standard ML
Standard ML (SML) is a General-purpose programming language, general-purpose, High-level programming language, high-level, Modular programming, modular, Functional programming, functional programming language with compile-time type checking and t ...
programming language does not provide any associative containers. However, various implementations of Standard ML do provide associative containers.
The library of the popular Standard ML of New Jersey
Standard ML of New Jersey (SML/NJ; Standard Meta-Language of New Jersey) is a compiler and integrated development environment for the programming language Standard ML. It is written in Standard ML, except for the runtime system in C language. It ...
(SML/NJ) implementation provides a signature (somewhat like an "interface"), ORD_MAP
, which defines a common interface for ordered functional (immutable) associative arrays. There are several general functors—BinaryMapFn
, ListMapFn
, RedBlackMapFn
, and SplayMapFn
—that allow you to create the corresponding type of ordered map (the types are a self-balancing binary search tree
In computer science, a self-balancing binary search tree (BST) is any node-based binary search tree that automatically keeps its height (maximal number of levels below the root) small in the face of arbitrary item insertions and deletions.Donald ...
, sorted association list
In computer programming and particularly in Lisp, an association list, often referred to as an alist, is a linked list in which each list element (or node) comprises a key and a value. The association list is said to ''associate'' the value wit ...
, red–black tree
In computer science, a red–black tree is a self-balancing binary search tree data structure noted for fast storage and retrieval of ordered information. The nodes in a red-black tree hold an extra "color" bit, often drawn as red and black, wh ...
, and splay tree
A splay tree is a binary search tree with the additional property that recently accessed elements are quick to access again. Like self-balancing binary search trees, a splay tree performs basic operations such as insertion, look-up and removal ...
, respectively) using a user-provided structure to describe the key type and comparator. The functor returns a structure in accordance with the ORD_MAP
interface. In addition, there are two pre-defined modules for associative arrays that employ integer keys: IntBinaryMap
and IntListMap
.
- structure StringMap = BinaryMapFn (struct
type ord_key = string
val compare = String.compare
end);
structure StringMap : ORD_MAP
- val m = StringMap.insert (StringMap.empty, "Sally Smart", "555-9999")
val m = StringMap.insert (m, "John Doe", "555-1212")
val m = StringMap.insert (m, "J. Random Hacker", "553-1337");
val m =
T
: string StringMap.map
- StringMap.find (m, "John Doe");
val it = SOME "555-1212" : string option
SML/NJ also provides a polymorphic hash table:
- exception NotFound;
exception NotFound
- val m : (string, string) HashTable.hash_table = HashTable.mkTable (HashString.hashString, op=) (3, NotFound);
val m =
HT
: (string,string) HashTable.hash_table
- HashTable.insert m ("Sally Smart", "555-9999");
val it = () : unit
- HashTable.insert m ("John Doe", "555-1212");
val it = () : unit
- HashTable.insert m ("J. Random Hacker", "553-1337");
val it = () : unit
HashTable.find m "John Doe"; (* returns NONE if not found *)
val it = SOME "555-1212" : string option
- HashTable.lookup m "John Doe"; (* raises the exception if not found *)
val it = "555-1212" : string
Monomorphic hash tables are also supported, using the HashTableFn
functor.
Another Standard ML implementation, Moscow ML
Standard ML (SML) is a general-purpose, high-level, modular, functional programming language with compile-time type checking and type inference. It is popular for writing compilers, for programming language research, and for developing theor ...
, also provides some associative containers. First, it provides polymorphic hash tables in the Polyhash
structure. Also, some functional maps from the SML/NJ library above are available as Binarymap
, Splaymap
, and Intmap
structures.
Tcl
There are two Tcl
TCL or Tcl or TCLs may refer to:
Business
* TCL Technology, a Chinese consumer electronics and appliance company
** TCL Electronics, a subsidiary of TCL Technology
* Texas Collegiate League, a collegiate baseball league
* Trade Centre Limited ...
facilities that support associative-array semantics. An "array" is a collection of variables. A "dict" is a full implementation of associative arrays.
array
set 555-9999
set john
set phonebook($john) 555-1212
set 553-1337
If there is a space character in the variable name, the name must be grouped using either curly brackets (no substitution performed) or double quotes (substitution is performed).
Alternatively, several array elements can be set by a single command, by presenting their mappings as a list (words containing whitespace are braced):
array set phonebook ist 555-9999 555-1212 553-1337
To access one array entry and put it to standard output:
puts $phonebook(Sally\ Smart)
Which returns this result:
555-9999
To retrieve the entire array as a dictionary:
array get phonebook
The result can be (order of keys is unspecified, not because the dictionary is unordered, but because the array is):
555-9999 553-1337 555-1212
dict
set phonebook ict create 555-9999 555-1212 553-1337
To look up an item:
dict get $phonebook
To iterate through a dict:
foreach $phonebook
Visual Basic
Visual Basic Visual Basic is a name for a family of programming languages from Microsoft. It may refer to:
* Visual Basic (.NET), the current version of Visual Basic launched in 2002 which runs on .NET
* Visual Basic (classic), the original Visual Basic suppo ...
can use the Dictionary class from the Microsoft Scripting Runtime (which is shipped with Visual Basic 6). There is no standard implementation common to all versions:
' Requires a reference to SCRRUN.DLL in Project Properties
Dim phoneBook As New Dictionary
phoneBook.Add "Sally Smart", "555-9999"
phoneBook.Item("John Doe") = "555-1212"
phoneBook("J. Random Hacker") = "553-1337"
For Each name In phoneBook
MsgBox name & " = " & phoneBook(name)
Next
Visual Basic .NET
Visual Basic .NET
Visual Basic (VB), originally called Visual Basic .NET (VB.NET), is a multi-paradigm, object-oriented programming language developed by Microsoft and implemented on .NET, Mono, and the .NET Framework. Microsoft launched VB.NET in 2002 as the ...
uses the collection classes provided by the .NET Framework.
Creation
The following code demonstrates the creation and population of a dictionary (see the C# example on this page for additional information):
Dim dic As New System.Collections.Generic.Dictionary(Of String, String)
dic.Add("Sally Smart", "555-9999")
dic("John Doe") = "555-1212"
dic.Item("J. Random Hacker") = "553-1337"
An alternate syntax would be to use a ''collection initializer'', which compiles down to individual calls to Add
:
Dim dic As New System.Collections.Dictionary(Of String, String) From
Access by key
Example demonstrating access (see C# access):
Dim sallyNumber = dic("Sally Smart")
' or
Dim sallyNumber = dic.Item("Sally Smart")
Dim result As String = Nothing
Dim sallyNumber = If(dic.TryGetValue("Sally Smart", result), result, "n/a")
Enumeration
Example demonstrating enumeration (see #C# enumeration):
' loop through the collection and display each entry.
For Each kvp As KeyValuePair(Of String, String) In dic
Console.WriteLine("Phone number for is ", kvp.Key, kvp.Value)
Next
Windows PowerShell
Unlike many other command line interpreter
A command-line interface (CLI) is a means of interacting with software via commands each formatted as a line of text. Command-line interfaces emerged in the mid-1960s, on computer terminals, as an interactive and more user-friendly alternativ ...
s, Windows PowerShell
PowerShell is a shell program developed by Microsoft for task automation and configuration management. As is typical for a shell, it provides a command-line interpreter for interactive use and a script interpreter for automation via a langua ...
has built-in, language-level support for defining associative arrays:
$phonebook = @
As in JavaScript, if the property name is a valid identifier, the quotes can be omitted:
$myOtherObject = @
Entries can be separated by either a semicolon or a newline:
$myOtherObject = @
Keys and values can be any .NET
The .NET platform (pronounced as "''dot net"'') is a free and open-source, managed code, managed computer software framework for Microsoft Windows, Windows, Linux, and macOS operating systems. The project is mainly developed by Microsoft emplo ...
object type:
$now = ateTime:Now
$tomorrow = $now.AddDays(1)
$ProcessDeletionSchedule = @
It is also possible to create an empty associative array and add single entries, or even other associative arrays, to it later on:
$phonebook = @
$phonebook += @
$phonebook += @
New entries can also be added by using the array index operator, the property operator, or the Add()
method of the underlying .NET object:
$phonebook = @
$phonebook Sally Smart'= '555-9999'
$phonebook.'John Doe' = '555-1212'
$phonebook.Add('J. Random Hacker', '553-1337')
To dereference assigned objects, the array index operator, the property operator, or the parameterized property Item()
of the .NET object can be used:
$phonebook Sally Smart'
$phonebook.'John Doe'
$phonebook.Item('J. Random Hacker')
You can loop through an associative array as follows:
$phonebook.Keys , foreach
An entry can be removed using the Remove()
method of the underlying .NET object:
$phonebook.Remove('Sally Smart')
Hash tables can be added:
$hash1 = @
$hash2 = @
$hash3 = $hash1 + $hash2
Data serialization formats support
Many data serialization formats also support associative arrays (see this table)
JSON
In JSON
JSON (JavaScript Object Notation, pronounced or ) is an open standard file format and electronic data interchange, data interchange format that uses Human-readable medium and data, human-readable text to store and transmit data objects consi ...
, associative arrays are also referred to as objects. Keys can only be strings.
TOML
TOML
Tom's Obvious, Minimal Language (TOML, originally ''Tom's Own Markup Language'') is a file format for configuration files. It is intended to be easy to read and write due to obvious semantics which aim to be "minimal", and it is designed to map u ...
is designed to map directly to a hash map. TOML refers to associative arrays as tables. Tables within TOML can be expressed in either an "unfolded" or an inline approach. Keys can only be strings. honebook"Sally Smart" = "555-9999"
"John Doe" = "555-1212"
"J. Random Hacker" = "555-1337"
phonebook =
YAML
YAML
YAML ( ) is a human-readable data serialization language. It is commonly used for configuration files and in applications where data is being stored or transmitted. YAML targets many of the same communications applications as Extensible Marku ...
associative arrays are also called map elements or key-value pairs. YAML places no restrictions on the types of keys; in particular, they are not restricted to being scalar or string values.
Sally Smart: 555-9999
John Doe: 555-1212
J. Random Hacker: 555-1337
References
{{Reflist, 2
Programming language comparison
*Mapping
Articles with example Julia code