Comparison Of Programming Languages (associative Arrays) on:  
[Wikipedia]  
[Google]  
[Amazon]
This comparison of programming languages (associative arrays) compares the features of
associative array
In computer science, an associative array, map, symbol table, or dictionary is an abstract data type that stores a collection of (key, value) pairs, such that each possible key appears at most once in the collection. In mathematical terms an ...
data structure
In computer science, a data structure is a data organization, management, and storage format that is usually chosen for Efficiency, efficient Data access, access to data. More precisely, a data structure is a collection of data values, the rel ...
s or array-lookup processing for over 40 computer
programming language
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming l ...
s.
Language support
The following is a comparison of
associative array
In computer science, an associative array, map, symbol table, or dictionary is an abstract data type that stores a collection of (key, value) pairs, such that each possible key appears at most once in the collection. In mathematical terms an ...
s (also "mapping", "hash", and "dictionary") in various programming languages.
AWK
AWK
AWK (''awk'') is a domain-specific language designed for text processing and typically used as a data extraction and reporting tool. Like sed and grep, it is a filter, and is a standard feature of most Unix-like operating systems.
The AWK l ...
has built-in, language-level support for associative arrays.
For example:
phonebook Sally Smart"= "555-9999"
phonebook John Doe"= "555-1212"
phonebook J. Random Hacker"= "555-1337"
The following code loops through an associated array and prints its contents:
for (name in phonebook)
The user can search for elements in an associative array, and delete elements from the array.
The following shows how multi-dimensional associative arrays can be simulated in standard AWK using concatenation and the built-in string-separator variable SUBSEP:
#
END
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, the
GLib
GLib is a bundle of three (formerly five) low-level system libraries written in C and developed mainly by GNOME. GLib's code was separated from GTK, so it can be used by software other than GNOME and has been developed in parallel ever si ...
library also supports associative arrays, along with many other advanced data types and is the recommended implementation of the GNU Project.
Similar to
GLib
GLib is a bundle of three (formerly five) low-level system libraries written in C and developed mainly by GNOME. GLib's code was separated from GTK, so it can be used by software other than GNOME and has been developed in parallel ever si ...
,
Apple
An apple is an edible fruit produced by an apple tree (''Malus domestica''). Apple trees are cultivated worldwide and are the most widely grown species in the genus '' Malus''. The tree originated in Central Asia, where its wild ances ...
's cross-platform
Core Foundation
Core Foundation (also called CF) is a C application programming interface (API) written by Apple for its operating systems, and is a mix of low-level routines and wrapper functions. Most Core Foundation routines follow a certain naming conventi ...
framework provides several basic data types. In particular, there are reference-counted CFDictionary and CFMutableDictionary.
C#
C# uses the collection classes provided by the
.NET Framework
The .NET Framework (pronounced as "''dot net"'') is a proprietary software framework developed by Microsoft that runs primarily on Microsoft Windows. It was the predominant implementation of the Common Language Infrastructure (CLI) until bein ...
. The most commonly used associative array type is
System.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
The domain name net is a generic top-level domain (gTLD) used in the Domain Name System of the Internet. The name is derived from the word ''network'', indicating it was originally intended for organizations involved in networking technologies ...
, also includes the
System.Collections.Immutable.Dictionary
type, which is implemented using an
AVL tree
In computer science, an AVL tree (named after inventors Adelson-Velsky and Landis) is a self-balancing binary search tree. It was the first such data structure to be invented. In an AVL tree, the heights of the two child subtrees of any node ...
. The methods that would normally mutate the object in-place instead return a new object that represents the state of the original object after mutation.
Creation
The following demonstrates three means of populating a mutable dictionary:
* the
Add
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
syntactic sugar
In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in a ...
(not applicable to C#, see
F# or
VB.NET examples).
var dictionary = new Dictionary();
dictionary.Add("Sally Smart", "555-9999");
dictionary John Doe"= "555-1212";
// Not allowed in C#.
// dictionary.Item("J. Random Hacker") = "553-1337";
dictionary J. Random Hacker"= "553-1337";
The dictionary can also be initialized during construction using a "collection initializer", which compiles to repeated calls to
Add
.
var dictionary = new Dictionary ;
Access by key
Values are primarily retrieved using the indexer (which throws an exception if the key does not exist) and the
TryGetValue
method, which has an output parameter for the sought value and a Boolean return-value indicating whether the key was found.
var sallyNumber = dictionary Sally Smart"
var sallyNumber = (dictionary.TryGetValue("Sally Smart", out var result) ? result : "n/a";
In this example, the
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 the
KeyValuePair
type, although there is no guarantee of order. For a sorted dictionary, the programmer could choose to use a
SortedDictionary
or use the
.Sort
LINQ
Language Integrated Query (LINQ, pronounced "link") is a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages, originally released as a major part of .NET Framework 3.5 in 2007.
LINQ extends the langua ...
extension method when enumerating.
The following demonstrates enumeration using a
foreach loop
In computer programming, foreach loop (or for each loop) is a control flow statement for traversing items in a collection. is usually used in place of a standard loop statement. Unlike other loop constructs, however, loops usually maintai ...
:
// loop through the collection and display each entry.
foreach (KeyValuePair kvp in dictionary)
C++
C++ has a form of associative array called
std::map
(see
Standard Template Library#Containers). One could create a phone-book map with the following code in C++:
#include
Or less efficiently, as this creates temporary
std::string
values:
#include
With the extension of
initialization lists in C++11, entries can be added during a map's construction as shown below:
#include
You can iterate through the list with the following code (C++03):
std::map::iterator curr, end;
for(curr = phone_book.begin(), end = phone_book.end(); curr != end; ++curr)
std::cout << curr->first << " = " << curr->second << std::endl;
The same task in C++11:
for(const auto& curr : phone_book)
std::cout << curr.first << " = " << curr.second << std::endl;
Using the structured binding available in
C++17
C++17 is a version of the ISO/ IEC 14882 standard for the C++ programming language. C++17 replaced the prior version of the C++ standard, called C++14, and was later replaced by C++20.
History
Before the C++ Standards Committee fixed a 3-yea ...
:
for (const auto& ame, number: phone_book)
In C++, the
std::map
class is
templated which allows the
data type
In computer science and computer programming, a data type (or simply type) is a set of possible values and a set of allowed operations on it. A data type tells the compiler or interpreter how the programmer intends to use the data. Most progra ...
s of keys and values to be different for different
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
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 ...
, C++11 defines a second map called
std::unordered_map
, which has the algorithmic characteristics of a hash table. This is a common vendor extension to the
Standard Template Library
The Standard Template Library (STL) is a software library originally designed by Alexander Stepanov for the C++ programming language that influenced many parts of the C++ Standard Library. It provides four components called ''algorithms'', ''co ...
(STL) as well, usually called
hash_map
, available from such implementations as SGI and STLPort.
Cobra
Initializing an empty dictionary and adding items in
Cobra:
Alternatively, a dictionary can be initialized with all items during construction:
The dictionary can be enumerated by a for-loop, but there is no guaranteed order:
ColdFusion Markup Language
A structure in
ColdFusion Markup Language
ColdFusion Markup Language, more commonly known as CFML, is a scripting language for web development that runs on the JVM, the .NET framework, and Google App Engine. Multiple commercial and open source implementations of CFML engines are availab ...
(CFML) is equivalent to an associative array:
dynamicKeyName = "John Doe";
phoneBook = ;
writeOutput(phoneBook.UnknownComic); // ???
writeDump(phoneBook); // entire struct
D
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:
int main()
Keys and values can be any types, but all the keys in an associative array must be of the same type, and the same goes for dependent values.
Looping through all properties and associated values, and printing them, can be coded as follows:
foreach (key, value; phone_book)
A property can be removed as follows:
phone_book.remove("Sally Smart");
Delphi
Delphi
Delphi (; ), in legend previously called Pytho (Πυθώ), in ancient times was a sacred precinct that served as the seat of Pythia, the major oracle who was consulted about important decisions throughout the ancient classical world. The oracl ...
supports several standard containers, including TDictionary
:
uses
SysUtils,
Generics.Collections;
var
PhoneBook: TDictionary;
Entry: TPair;
begin
PhoneBook := TDictionary.Create;
PhoneBook.Add('Sally Smart', '555-9999');
PhoneBook.Add('John Doe', '555-1212');
PhoneBook.Add('J. Random Hacker', '553-1337');
for Entry in PhoneBook do
Writeln(Format('Number for %s: %s', ntry.Key, Entry.Value);
end.
Pre-2009 Delphi versions do not support associative arrays directly. Such arrays can be simulated using the TStrings class:
procedure TForm1.Button1Click(Sender: TObject);
var
DataField: TStrings;
i: Integer;
begin
DataField := TStringList.Create;
DataField.Values Sally Smart':= '555-9999';
DataField.Values John Doe':= '555-1212';
DataField.Values J. Random Hacker':= '553-1337';
// access an entry and display it in a message box
ShowMessage(DataField.Values Sally Smart';
// loop through the associative array
for i := 0 to DataField.Count - 1 do
begin
ShowMessage('Number for ' + DataField.Names + ': ' + DataField.ValueFromIndex ;
end;
DataField.Free;
end;
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 of tuple
In mathematics, a tuple is a finite ordered list (sequence) of elements. An -tuple is a sequence (or ordered list) of elements, where is a non-negative integer. There is only one 0-tuple, referred to as ''the empty tuple''. An -tuple is defi ...
s, where the first element of each tuple is a key, and the second is a value. Functions for operating on keylists are provided in the lists
module.
PhoneBook =
,
Accessing an element of the keylist can be done with the lists:keyfind/3
function:
= lists:keyfind("Sally Smith", 1, PhoneBook),
io:format("Phone number: ~s~n", hone Honing is a kind of metalworking.
Hone may also refer to:
* Hone (name) (incl. Hōne), a list of people with the surname, given name or nickname
* Hõne language, spoken in Gombe State and Taraba State, Nigeria
* Hône
Hône ( Valdôtain: (lo ...
.
Dictionaries
Dictionaries are implemented in the dict
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:
PhoneBook1 = dict:new(),
PhoneBook2 = dict:store("Sally Smith", "555-9999", Dict1),
PhoneBook3 = dict:store("John Doe", "555-1212", Dict2),
PhoneBook = dict:store("J. Random Hacker", "553-1337", Dict3).
Such a serial initialization would be more idiomatically represented in Erlang with the appropriate function:
PhoneBook = dict:from_list(
,
.
The dictionary can be accessed using the dict:find/2
function:
= dict:find("Sally Smith", PhoneBook),
io:format("Phone: ~s~n", hone Honing is a kind of metalworking.
Hone may also refer to:
* Hone (name) (incl. Hōne), a list of people with the surname, given name or nickname
* Hõne language, spoken in Gombe State and Taraba State, Nigeria
* Hône
Hône ( Valdôtain: (lo ...
.
In both cases, any Erlang term can be used as the key. Variations include the 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 #
:
PhoneBook = #.
Basic functions to interact with maps are available from the maps
module. For example, the maps:find/2
function returns the value associated with a key:
= maps:find("Sally Smith", PhoneBook),
io:format("Phone: ~s~n", hone Honing is a kind of metalworking.
Hone may also refer to:
* Hone (name) (incl. Hōne), a list of people with the surname, given name or nickname
* Hõne language, spoken in Gombe State and Taraba State, Nigeria
* Hône
Hône ( Valdôtain: (lo ...
.
Unlike dictionaries, maps can be pattern matched upon:
# = PhoneBook,
io:format("Phone: ~s~n", hone Honing is a kind of metalworking.
Hone may also refer to:
* Hone (name) (incl. Hōne), a list of people with the surname, given name or nickname
* Hõne language, spoken in Gombe State and Taraba State, Nigeria
* Hône
Hône ( Valdôtain: (lo ...
.
Erlang also provides syntax sugar for functional updates—creating a new map based on an existing one, but with modified values or additional keys:
PhoneBook2 = PhoneBook#
F#
Map<'Key,'Value>
At runtime, F# provides the Collections.Map<'Key,'Value>
type, which is an immutable AVL tree
In computer science, an AVL tree (named after inventors Adelson-Velsky and Landis) is a self-balancing binary search tree. It was the first such data structure to be invented. In an AVL tree, the heights of the two child subtrees of any node ...
.
=Creation
=
The following example calls the Map
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).
let numbers =
"Sally Smart", "555-9999";
"John Doe", "555-1212";
"J. Random Hacker", "555-1337"
, > Map
=Access by key
=
Values can be looked up via one of the Map
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 option type
In programming languages (especially functional programming languages) and type theory, an option type or maybe type is a polymorphic type that represents encapsulation of an optional value; e.g., it is used as the return type of functions whic ...
with a value of Some
, for a successful lookup, or None
, for an unsuccessful one. Pattern matching
In computer science, pattern matching is the act of checking a given sequence of tokens for the presence of the constituents of some pattern. In contrast to pattern recognition, the match usually has to be exact: "either it will or will not be ...
can then be used to extract the raw value from the result, or a default value can be set.
let sallyNumber = numbers. Sally Smart"// or
let sallyNumber = numbers.Item("Sally Smart")
let sallyNumber =
match numbers.TryFind("Sally Smart") with
, Some(number) -> number
, None -> "n/a"
In both examples above, the 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
The .NET Framework (pronounced as "''dot net"'') is a proprietary software framework developed by Microsoft that runs primarily on Microsoft Windows. It was the predominant implementation of the Common Language Infrastructure (CLI) until bein ...
, including the type (which is implemented as a hash table
In computing, a hash table, also known as hash map, is a data structure that implements an associative array or dictionary. It is an abstract data type that maps keys to values. A hash table uses a hash function to compute an ''index'', ...
), which is the primary associative array type used in C# and Visual Basic. This type may be preferred when writing code that is intended to operate with other languages on the .NET Framework, or when the performance characteristics of a hash table are preferred over those of an AVL tree.
=Creation
=
The dict
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>
.
let numbers =
"Sally Smart", "555-9999";
"John Doe", "555-1212";
"J. Random Hacker", "555-1337"
, > dict
When a mutable dictionary is needed, the constructor of can be called directly. See the C# example on this page for additional information.
let numbers = System.Collections.Generic.Dictionary()
numbers.Add("Sally Smart", "555-9999")
numbers. John Doe"<- "555-1212"
numbers.Item("J. Random Hacker") <- "555-1337"
=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.
let sallyNumber =
let mutable result = ""
if numbers.TryGetValue("Sally Smart", &result) then result else "n/a"
F# also allows the function to be called as if it had no output parameter and instead returned a tuple containing its regular return value and the value assigned to the output parameter:
let sallyNumber =
match numbers.TryGetValue("Sally Smart") with
, true, number -> number
, _ -> "n/a"
Enumeration
A dictionary or map can be enumerated using Seq.map
.
// loop through the collection and display each entry.
numbers , > Seq.map (fun kvp -> printfn "Phone number for %O is %O" kvp.Key kvp.Value)
FoxPro
Visual FoxPro
Visual FoxPro is a Microsoft data-centric procedural programming language with object-oriented programming (OOP) features.
It was derived from FoxPro (originally known as FoxBASE) which was developed by Fox Software beginning in 1984. Fox Techno ...
implements mapping with the Collection Class.
mapping = NEWOBJECT("Collection")
mapping.Add("Daffodils", "flower2") && Add(object, key) – key must be character
index = mapping.GetKey("flower2") && returns the index value 1
object = mapping("flower2") && returns "Daffodils" (retrieve by key)
object = mapping(1) && returns "Daffodils" (retrieve by index)
GetKey returns 0 if the key is not found.
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:
phone_book := make(maptring
Tring is a market town and civil parish in the Borough of Dacorum, Hertfordshire, England. It is situated in a gap passing through the Chiltern Hills, classed as an Area of Outstanding Natural Beauty, from Central London. Tring is linked t ...
string) // make an empty map
phone_book Sally Smart"= "555-9999"
phone_book John Doe"= "555-1212"
phone_book J. Random Hacker"= "553-1337"
A map literal:
phone_book := maptring
Tring is a market town and civil parish in the Borough of Dacorum, Hertfordshire, England. It is situated in a gap passing through the Chiltern Hills, classed as an Area of Outstanding Natural Beauty, from Central London. Tring is linked t ...
string
Iterating through a map:
// over both keys and values
for key, value := range phone_book
// over just keys
for key := range phone_book
Haskell
The Haskell
Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lan ...
programming language provides only one kind of associative container – a list of pairs:
m = "Sally Smart", "555-9999"), ("John Doe", "555-1212"), ("J. Random Hacker", "553-1337")
main = print (lookup "John Doe" m)
output:
Just "555-1212"
Note that the lookup function returns a "Maybe" value, which is "Nothing" if not found, or "Just 'result when found.
The Glasgow Haskell Compiler
The Glasgow Haskell Compiler (GHC) is an open-source native code compiler for the functional programming language Haskell.
It provides a cross-platform environment for the writing and testing of Haskell code and it supports numerous extension ...
(GHC), the most commonly used implementation of Haskell, provides two more types of associative containers. Other implementations may also provide these.
One is polymorphic functional maps (represented as immutable balanced binary trees):
import qualified Data.Map as M
m = M.insert "Sally Smart" "555-9999" M.empty
m' = M.insert "John Doe" "555-1212" m
m'' = M.insert "J. Random Hacker" "553-1337" m'
main = print (M.lookup "John Doe" m'' :: Maybe String)
output:
Just "555-1212"
A specialized version for integer keys also exists as Data.IntMap.
Finally, a polymorphic hash table:
import qualified Data.HashTable as H
main = do m <- H.new () H.hashString
H.insert m "Sally Smart" "555-9999"
H.insert m "John Doe" "555-1212"
H.insert m "J. Random Hacker" "553-1337"
foo <- H.lookup m "John Doe"
print foo
output:
Just "555-1212"
Lists of pairs and functional maps both provide a purely functional interface, which is more idiomatic in Haskell. In contrast, hash tables provide an imperative interface in the IO monad.
Java
In Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
associative arrays are implemented as "maps", which are part of the Java collections framework
The Java collections framework is a set of classes and interfaces that implement commonly reusable collection data structures.
Although referred to as a framework, it works in a manner of a library. The collections framework provides both int ...
. Since J2SE
Java Platform, Standard Edition (Java SE) is a computing platform for development and deployment of portable code for desktop and server environments. Java SE was formerly known as Java 2 Platform, Standard Edition (J2SE).
The platform uses Jav ...
5.0 and the introduction of generics
Generic or generics may refer to:
In business
* Generic term, a common name used for a range or class of similar things not protected by trademark
* Generic brand, a brand for a product that does not have an associated brand or trademark, other ...
into Java, collections can have a type specified; for example, an associative array that maps strings to strings might be specified as follows:
Map phoneBook = new HashMap();
phoneBook.put("Sally Smart", "555-9999");
phoneBook.put("John Doe", "555-1212");
phoneBook.put("J. Random Hacker", "555-1337");
The method is used to access a key; for example, the value of the expression phoneBook.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
Override may refer to:
* Dr. Gregory Herd, a Marvel Comics character formerly named Override
* Manual override, a function where an automated system is placed under manual control
* Method overriding, a subclassing feature in Object Oriented pro ...
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'',
a.equals(b) b.equals(a)
if a.equals(b), then a.hashCode() b.hashCode()
In order to maintain this contract, a class that overrides 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 immutable
In object-oriented computer programming, object-oriented and Functional programming, functional programming, an immutable object (unchangeable object) is an object (computer science), object whose state cannot be modified after it is created.Goet ...
properties of the object.
Analogously, TreeMap, and other sorted data structures, require that an ordering be defined on the data type. Either the data type must already have defined its own ordering, by implementing the interface; or a custom must be provided at the time the map is constructed. As with HashMap above, the relative ordering of keys in a TreeMap should not change once they have been inserted into the map.
JavaScript
JavaScript
JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
(and its standardized version, ECMAScript
ECMAScript (; ES) is a JavaScript standard intended to ensure the interoperability of web pages across different browsers. It is standardized by Ecma International in the documenECMA-262
ECMAScript is commonly used for client-side scriptin ...
) is a prototype-based object-oriented
Object-oriented programming (OOP) is a programming paradigm based on the concept of " objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of ...
language.
Map and WeakMap
Modern JavaScript handles associative arrays, using the Map
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:
const phoneBook = new Map( ["Sally Smart", "555-9999"
["John Doe", "555-1212"">quot;Sally_Smart",_"555-9999".html" ;"title=" ["Sally Smart", "555-9999""> ["Sally Smart", "555-9999"
["John Doe", "555-1212"
["J. Random Hacker", "553-1337"],
]);
Alternatively, you can initialize an empty map and then add items:
const phoneBook = new Map();
phoneBook.set("Sally Smart", "555-9999");
phoneBook.set("John Doe", "555-1212");
phoneBook.set("J. Random Hacker", "553-1337");
=Access by key
=
Accessing an element of the map can be done with the get
method:
const sallyNumber = phoneBook.get("Sally Smart");
In this example, the value 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:
// loop through the collection and display each entry.
for (const ame, numberof phoneBook)
A key can be removed as follows:
phoneBook.delete("Sally Smart");
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:
const myObject = ;
To prevent the lookup from using the prototype's properties, you can use the Object.setPrototypeOf
function:
Object.setPrototypeOf(myObject, null);
As of ECMAScript 5 (ES5), the prototype can also be bypassed by using Object.create(null)
:
const myObject = Object.create(null);
Object.assign(myObject, );
If the property name is a valid identifier, the quotes can be omitted, e.g.:
const myOtherObject = ;
Lookup is written using property-access notation, either square brackets, which always work, or dot notation, which only works for identifier keys:
myObject John Doe"myOtherObject.foo
You can also loop through all enumerable properties and associated values as follows (a for-in loop):
for (const property in myObject)
Or (a for-of loop):
for (const roperty, valueof Object.entries(myObject))
A property can be removed as follows:
delete myObject Sally Smart"
As mentioned before, properties are strings and symbols. Since every native object and primitive can be implicitly converted to a string, you can do:
myObject // key is "1"; note that myObject myObject 1"myObject "a", "b" // key is "a,b"
myObject[] // key is "hello world"
In modern JavaScript it's considered bad form to use the Array type as an associative array. Consensus is that the Object type and 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.
Se
JavaScript Array And Object Prototype Awareness Day
for more information on the issue.
Julia
In Julia
Julia is usually a feminine given name. It is a Latinate feminine form of the name Julio and Julius. (For further details on etymology, see the Wiktionary entry "Julius".) The given name ''Julia'' had been in use throughout Late Antiquity (e ...
, the following operations manage associative arrays.
Declare dictionary:
phonebook = Dict( "Sally Smart" => "555-9999", "John Doe" => "555-1212", "J. Random Hacker" => "555-1337" )
Access element:
phonebook Sally Smart"
Add element:
phonebook New Contact"= "555-2222"
Delete element:
delete!(phonebook, "Sally Smart")
Get keys and values as iterables:
keys(phonebook)
values(phonebook)
KornShell 93, and compliant shells
In KornShell
KornShell (ksh) is a Unix shell which was developed by David Korn at Bell Labs in the early 1980s and announced at USENIX on July 14, 1983. The initial development was based on Bourne shell source code. Other early contributors were Bell ...
93, and compliant shells (ksh93, bash4...), the following operations can be used with associative arrays.
Definition:
typeset -A phonebook; # ksh93; in bash4+, "typeset" is a synonym of the more preferred "declare", which works identically in this case
phonebook=( Sally Smart""555-9999" John Doe""555-1212" J. Random Hacker"">J._Random_Hacker.html" ;"title="J. Random Hacker">J. Random Hacker""555-1337");
Dereference:
$;
Lisp
Lisp programming language">Lisp
A lisp is a speech impairment in which a person misarticulates sibilants (, , , , , , , ). These misarticulations often result in unclear speech.
Types
* A frontal lisp occurs when the tongue is placed anterior to the target. Interdental lispi ...
was originally conceived as a "LISt Processing" language, and one of its most important data types is the linked list, which can be treated as an
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 with ...
("alist").
'(("Sally Smart" . "555-9999")
("John Doe" . "555-1212")
("J. Random Hacker" . "553-1337"))
The syntax
(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 A scheme is a systematic plan for the implementation of a certain idea.
Scheme or schemer may refer to:
Arts and entertainment
* ''The Scheme'' (TV series), a BBC Scotland documentary series
* The Scheme (band), an English pop band
* ''The Schem ...
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
Common Lisp
Common Lisp (CL) is a dialect of the Lisp programming language, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fr ...
, each of these working non-destructively.
To add an entry the
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.
(let ((phone-book NIL))
(setf phone-book (acons "Sally Smart" "555-9999" phone-book))
(setf phone-book (acons "John Doe" "555-1212" phone-book))
(setf phone-book (acons "J. Random Hacker" "555-1337" phone-book)))
This function can be construed as an accommodation for
cons
operations.
;; The effect of
;; (cons (cons KEY VALUE) ALIST)
;; is equivalent to
;; (acons KEY VALUE ALIST)
(let ((phone-book '(("Sally Smart" . "555-9999") ("John Doe" . "555-1212"))))
(cons (cons "J. Random Hacker" "555-1337") phone-book))
Of course, the destructive
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.
(push (cons "Dummy" "123-4567") phone-book)
Searching for an entry by its key is performed via
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 "John Doe" phone-book :test #'string=)
Two generalizations of
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
.
;; Find the first entry whose key equals "John Doe".
(assoc-if
#'(lambda (key)
(string= key "John Doe"))
phone-book)
;; Finds the first entry whose key is neither "Sally Smart" nor "John Doe"
(assoc-if-not
#'(lambda (key)
(member key '("Sally Smart" "John Doe") :test #'string=))
phone-book)
The inverse process, the detection of an entry by its value, utilizes
rassoc
.
;; Find the first entry with a value of "555-9999".
;; We test the entry string values with the "string=" predicate.
(rassoc "555-9999" phone-book :test #'string=)
The corresponding generalizations
rassoc-if
and
rassoc-if-not
exist.
;; Finds the first entry whose value is "555-9999".
(rassoc-if
#'(lambda (value)
(string= value "555-9999"))
phone-book)
;; Finds the first entry whose value is not "555-9999".
(rassoc-if-not
#'(lambda (value)
(string= value "555-9999"))
phone-book)
All of the previous entry search functions can be replaced by general list-centric variants, such as
find
,
find-if
,
find-if-not
, as well as pertinent functions like
position
and its derivates.
;; Find an entry with the key "John Doe" and the value "555-1212".
(find (cons "John Doe" "555-1212") phone-book :test #'equal)
Deletion, lacking a specific counterpart, is based upon the list facilities, including destructive ones.
;; Create and return an alist without any entry whose key equals "John Doe".
(remove-if
#'(lambda (entry)
(string= (car entry) "John Doe"))
phone-book)
Iteration is accomplished with the aid of any function that expects a list.
;; Iterate via "map".
(map NIL
#'(lambda (entry)
(destructuring-bind (key . value) entry
(format T "~&~s => ~s" key value)))
phone-book)
;; Iterate via "dolist".
(dolist (entry phone-book)
(destructuring-bind (key . value) entry
(format T "~&~s => ~s" key value)))
These being structured lists, processing and transformation operations can be applied without constraints.
;; Return a vector of the "phone-book" values.
(map 'vector #'cdr phone-book)
;; Destructively modify the "phone-book" via "map-into".
(map-into phone-book
#'(lambda (entry)
(destructuring-bind (key . value) entry
(cons (reverse key) (reverse value))))
phone-book)
Because of their linear nature, alists are used for relatively small sets of data.
Common Lisp
Common Lisp (CL) is a dialect of the Lisp programming language, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fr ...
also supports a
hash table
In computing, a hash table, also known as hash map, is a data structure that implements an associative array or dictionary. It is an abstract data type that maps keys to values. A hash table uses a hash function to compute an ''index'', ...
data type, and for
Scheme A scheme is a systematic plan for the implementation of a certain idea.
Scheme or schemer may refer to:
Arts and entertainment
* ''The Scheme'' (TV series), a BBC Scotland documentary series
* The Scheme (band), an English pop band
* ''The Schem ...
they are implemented in
SRFI 69. Hash tables have greater overhead than alists, but provide much faster access when there are many elements. A further characteristic is the fact that Common Lisp hash tables do not, as opposed to association lists, maintain the order of entry insertion.
Common Lisp hash tables are constructed via the
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.
(let ((phone-book (make-hash-table :test #'equal)))
(setf (gethash "Sally Smart" phone-book) "555-9999")
(setf (gethash "John Doe" phone-book) "555-1212")
(setf (gethash "J. Random Hacker" phone-book) "553-1337"))
The
gethash
function permits obtaining the value associated with a key.
(gethash "John Doe" phone-book)
Additionally, a default value for the case of an absent key may be specified.
(gethash "Incognito" phone-book 'no-such-key)
An invocation of
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.
(multiple-value-bind (value contains-key) (gethash "Sally Smart" phone-book)
(if contains-key
(format T "~&The associated value is: ~s" value)
(format T "~&The key could not be found.")))
Use
remhash
for deleting the entry associated with a key.
(remhash "J. Random Hacker" phone-book)
clrhash
completely empties the hash table.
(clrhash phone-book)
The dedicated
maphash
function specializes in iterating hash tables.
(maphash
#'(lambda (key value)
(format T "~&~s => ~s" key value))
phone-book)
Alternatively, the
loop
construct makes provisions for iterations, through keys, values, or conjunctions of both.
;; Iterate the keys and values of the hash table.
(loop
for key being the hash-keys of phone-book
using (hash-value value)
do (format T "~&~s => ~s" key value))
;; Iterate the values of the hash table.
(loop
for value being the hash-values of phone-book
do (print value))
A further option invokes
with-hash-table-iterator
, an iterator-creating macro, the processing of which is intended to be driven by the caller.
(with-hash-table-iterator (entry-generator phone-book)
(loop do
(multiple-value-bind (has-entry key value) (entry-generator)
(if has-entry
(format T "~&~s => ~s" key value)
(loop-finish)))))
It is easy to construct composite abstract data types in Lisp, using structures or object-oriented programming features, in conjunction with lists, arrays, and hash tables.
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:
mapping phone_book = ([]);
phone_book Sally Smart"= "555-9999";
phone_book John Doe"= "555-1212";
phone_book J. Random Hacker"= "555-1337";
Mappings are accessed for reading using the indexing operator in the same way as they are for writing, as shown above. So phone_book
Sally Smart"would return the string "555-9999", and phone_book
John Smith"would return 0. Testing for presence is done using the function member(), e.g.
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
MudOS
LPMud, abbreviated LP, is a family of MUD server software. Its first instance, the original LPMud game driver, was developed in 1989 by Lars Pensjö (hence the LP in LPMud). LPMud was innovative in its separation of the MUD infrastructure into a ...
family do not support multivalued mappings.) Example syntax:
mapping phone_book = ( 2;
phone_book Sally Smart", 0= "555-9999";
phone_book Sally Smart", 1= "99 Sharp Way";
phone_book John Doe", 0= "555-1212";
phone_book John Doe", 1= "3 Nigma Drive";
phone_book J. Random Hacker", 0= "555-1337";
phone_book J. Random Hacker", 1= "77 Massachusetts Avenue";
LPC drivers modern enough to support a foreach() construct use it to iterate through their mapping types.
Lua
In
Lua
Lua or LUA may refer to:
Science and technology
* Lua (programming language)
* Latvia University of Agriculture
* Last universal ancestor, in evolution
Ethnicity and language
* Lua people, of Laos
* Lawa people, of Thailand sometimes referred t ...
, "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:
phone_book =
aTable =
If the key is a valid identifier (not a reserved word), the quotes can be omitted. Identifiers are case sensitive.
Lookup is written using either square brackets, which always works, or dot notation, which only works for identifier keys:
print(aTable John Doe"45))
x = aTable.subTable.k
You can also loop through all keys and associated values with iterators or for-loops:
simple =
function FormatElement(key, value)
return " .. tostring(key) .. "= " .. value .. ", "
end
-- Iterate on all keys
table.foreach(simple, function (k, v) io.write(FormatElement(k, v)) end)
print""
for k, v in pairs(simple) do io.write(FormatElement(k, v)) end
print""
k= nil
repeat
k, v = next(simple, k)
if k ~= nil then io.write(FormatElement(k, v)) end
until k nil
print""
An entry can be removed by setting it to nil:
simple.x = nil
Likewise, you can overwrite values or add them:
simple %'= "percent"
simple !'= 111
Mathematica and Wolfram Language
Mathematica
Wolfram Mathematica is a software system with built-in libraries for several areas of technical computing that allow machine learning, statistics, symbolic computation, data manipulation, network analysis, time series analysis, NLP, optimi ...
and
Wolfram Language
The Wolfram Language ( ) is a general multi-paradigm programming language developed by Wolfram Research. It emphasizes symbolic computation, functional programming, and rule-based programming and can employ arbitrary structures and data. It is ...
use the Association expression to represent associative arrays.
phonebook = <, "Sally Smart" -> "555-9999",
"John Doe" -> "555-1212",
"J. Random Hacker" -> "553-1337" , >;
To access:
phonebook Key["Sally Smart"">quot;Sally_Smart".html" ;"title="Key["Sally Smart"">Key["Sally Smart"
If the keys are strings, the Key keyword is not necessary, so:
phonebook"Sally Smart"
To list keys: and values
Keys[phonebook]
Values[phonebook]
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
Cocoa may refer to:
Chocolate
* Chocolate
* ''Theobroma cacao'', the cocoa tree
* Cocoa bean, seed of ''Theobroma cacao''
* Chocolate liquor, or cocoa liquor, pure, liquid chocolate extracted from the cocoa bean, including both cocoa butter and ...
and
GNUstep
GNUstep is a free software implementation of the Cocoa (formerly OpenStep) Objective-C frameworks, widget toolkit, and application development tools for Unix-like operating systems and Microsoft Windows. It is part of the GNU Project.
GNUst ...
, written in
Objective-C
Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its N ...
, handle associative arrays using
NSMutableDictionary
(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).
NSMutableDictionary *aDictionary = NSMutableDictionary allocinit];
Dictionary setObject:@"555-9999" forKey:@"Sally Smart"
Dictionary setObject:@"555-1212" forKey:@"John Doe"
Dictionary setObject:@"553-1337" forKey:@"Random Hacker"
To access assigned objects, this command may be used:
id anObject = Dictionary objectForKey:@"Sally Smart"
All keys or values can be enumerated using
NSEnumerator
:
NSEnumerator *keyEnumerator = Dictionary keyEnumerator
id key;
while ((key = eyEnumerator nextObject)
In Mac OS X 10.5+ and iPhone OS, dictionary keys can be enumerated more concisely using the
NSFastEnumeration
construct:
for (id key in aDictionary)
What is even more practical, structured data graphs may be easily created using
Cocoa
Cocoa may refer to:
Chocolate
* Chocolate
* ''Theobroma cacao'', the cocoa tree
* Cocoa bean, seed of ''Theobroma cacao''
* Chocolate liquor, or cocoa liquor, pure, liquid chocolate extracted from the cocoa bean, including both cocoa butter and ...
, especially
NSDictionary
(
NSMutableDictionary
). This can be illustrated with this compact example:
NSDictionary *aDictionary =
[NSDictionary dictionaryWithObjectsAndKeys:
[NSDictionary dictionaryWithObjectsAndKeys:
@"555-9999", @"Sally Smart",
@"555-1212", @"John Doe",
nil], @"students",
[NSDictionary dictionaryWithObjectsAndKeys:
@"553-1337", @"Random Hacker",
nil], @"hackers",
nil];
Relevant fields can be quickly accessed using key paths:
id anObject = Dictionary valueForKeyPath:@"students.Sally Smart"
OCaml
The
OCaml
OCaml ( , formerly Objective Caml) is a general-purpose, multi-paradigm programming language which extends the Caml dialect of ML with object-oriented features. OCaml was created in 1996 by Xavier Leroy, Jérôme Vouillon, Damien Doligez, D ...
programming language provides three different associative containers. The simplest is a list of pairs:
# let m = "Sally Smart", "555-9999";
"John Doe", "555-1212";
"J. Random Hacker", "553-1337";
val m : (string * string) list = ("Sally Smart", "555-9999");
("John Doe", "555-1212");
("J. Random Hacker", "553-1337")
# List.assoc "John Doe" m;;
- : string = "555-1212"
The second is a polymorphic hash table:
# let m = Hashtbl.create 3;;
val m : ('_a, '_b) Hashtbl.t =
# Hashtbl.add m "Sally Smart" "555-9999";
Hashtbl.add m "John Doe" "555-1212";
Hashtbl.add m "J. Random Hacker" "553-1337";;
- : unit = ()
# Hashtbl.find m "John Doe";;
- : string = "555-1212"
The code above uses OCaml's default hash function
Hashtbl.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):
# module StringMap = Map.Make(String);;
...
# let m = StringMap.add "Sally Smart" "555-9999" StringMap.empty
let m = StringMap.add "John Doe" "555-1212" m
let m = StringMap.add "J. Random Hacker" "553-1337" m;;
val m : string StringMap.t =
# StringMap.find "John Doe" m;;
- : string = "555-1212"
Note that in order to use
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
The
OptimJ
OptimJ is an extension for Java with language support for writing optimization models and abstractions for bulk data processing. The extensions and the proprietary product implementing the extensions were developed by Ateji which went out of busine ...
programming language is an extension of Java 5. As does Java, Optimj provides maps; but OptimJ also provides true associative arrays. Java arrays are indexed with non-negative integers; associative arrays are indexed with any type of key.
Stringtring
Tring is a market town and civil parish in the Borough of Dacorum, Hertfordshire, England. It is situated in a gap passing through the Chiltern Hills, classed as an Area of Outstanding Natural Beauty, from Central London. Tring is linked t ...
phoneBook = ;
// Stringtring
Tring is a market town and civil parish in the Borough of Dacorum, Hertfordshire, England. It is situated in a gap passing through the Chiltern Hills, classed as an Area of Outstanding Natural Beauty, from Central London. Tring is linked t ...
is not a java type but an optimj type:
// associative array of strings indexed by strings.
// iterate over the values
for (String number : phoneBook)
// The previous statement prints: "555-9999" "555-1212" "553-1337"
// iterate over the keys
for (String name : phoneBook.keys)
// phoneBookame #REDIRECT AME
{{redirect category shell, {{R from other capitalisation{{R from ambiguous page ...
access a value by a key (it looks like java array access)
// i.e. phoneBook John Doe"returns "555-1212"
Of course, it is possible to define multi-dimensional arrays, to mix Java arrays and associative arrays, to mix maps and associative arrays.
inttring
Tring is a market town and civil parish in the Borough of Dacorum, Hertfordshire, England. It is situated in a gap passing through the Chiltern Hills, classed as an Area of Outstanding Natural Beauty, from Central London. Tring is linked t ...
] oublea;
java.util.Mapbject Integer> b;
Perl 5
Perl 5
Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...
has built-in, language-level support for associative arrays. Modern Perl refers to associative arrays as ''hashes''; the term ''associative array'' is found in older documentation but is considered somewhat archaic. Perl 5 hashes are flat: keys are strings and values are scalars. However, values may be
references
Reference is a relationship between objects in which one object designates, or acts as a means by which to connect to or link to, another object. The first object in this relation is said to ''refer to'' the second object. It is called a '' name'' ...
to arrays or other hashes, and the standard Perl 5 module Tie::RefHash enables hashes to be used with reference keys.
A hash variable is marked by a
%
sigil
A sigil () is a type of symbol used in magic. The term has usually referred to a pictorial signature of a deity or spirit. In modern usage, especially in the context of chaos magic, sigil refers to a symbolic representation of the practitio ...
, to distinguish it from scalar, array, and other data types. A hash literal is a key-value list, with the preferred form using Perl's
=>
token, which is semantically mostly identical to the comma and makes the key-value association clearer:
my %phone_book = (
'Sally Smart' => '555-9999',
'John Doe' => '555-1212',
'J. Random Hacker' => '553-1337',
);
Accessing a hash element uses the syntax
$hash_name
– the key is surrounded by
curly braces
A bracket is either of two tall fore- or back-facing punctuation marks commonly used to isolate a segment of text or data from its surroundings. Typically deployed in symmetric pairs, an individual bracket may be identified as a 'left' or 'r ...
and the hash name is prefixed by a
$
, 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:
foreach $name (keys %phone_book)
One can iterate through (key, value) pairs using the
each
function:
while (($name, $number) = each %phone_book)
A hash "reference", which is a scalar value that points to a hash, is specified in literal form using curly braces as delimiters, with syntax otherwise similar to specifying a hash literal:
my $phone_book = ;
Values in a hash reference are accessed using the dereferencing operator:
print $phone_book->;
When the hash contained in the hash reference needs to be referred to as a whole, as with the
keys
function, the syntax is as follows:
foreach $name (keys %)
Perl 6 (Raku)
Perl 6
Raku is a member of the Perl family of programming languages. Formerly known as Perl 6, it was renamed in October 2019. Raku introduces elements of many modern and historical languages. Compatibility with Perl was not a goal, though a compatibil ...
, 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
%
sigil
A sigil () is a type of symbol used in magic. The term has usually referred to a pictorial signature of a deity or spirit. In modern usage, especially in the context of chaos magic, sigil refers to a symbolic representation of the practitio ...
, to visually distinguish it from scalar, array, and other data types, and to define its behaviour towards iteration. A hash literal is a key-value list, with the preferred form using Perl's
=>
token, which makes the key-value association clearer:
my %phone-book =
'Sally Smart' => '555-9999',
'John Doe' => '555-1212',
'J. Random Hacker' => '553-1337',
;
Accessing a hash element uses the syntax
%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:
for %phone-book.keys -> $name
By default, when iterating through a hash, one gets key–value pairs.
for %phone-book -> $entry
It is also possible to get alternating key values and value values by using the
kv
method:
for %phone-book.kv -> $name, $number
Raku doesn't have any references. Hashes can be passed as single parameters that are not flattened. If you want to make sure that a subroutine only accepts hashes, use the ''%'' sigil in the Signature.
sub list-phone-book(%pb)
list-phone-book(%phone-book);
In compliance with
gradual typing
Gradual typing is a type system in which some variables and expressions may be given types and the correctness of the typing is checked at compile time (which is static typing) and some expressions may be left untyped and eventual type errors a ...
, hashes may be subjected to type constraints, confining a set of valid keys to a certain type.
# Define a hash whose keys may only be integer numbers ("Int" type).
my %numbersWithNames;
# Keys must be integer numbers, as in this case.
%numbersWithNames.push(1 => "one");
# This will cause an error, as strings as keys are invalid.
%numbersWithNames.push("key" => "two");
PHP
PHP
PHP is a General-purpose programming language, general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementati ...
's built-in array type is, in reality, an associative array. Even when using numerical indexes, PHP internally stores arrays as associative arrays. So, PHP can have non-consecutively numerically indexed arrays. The keys have to be of integer (floating point numbers are truncated to integer) or string type, while values can be of arbitrary types, including other arrays and objects. The arrays are heterogeneous: a single array can have keys of different types. PHP's associative arrays can be used to represent trees, lists, stacks, queues, and other common data structures not built into PHP.
An associative array can be declared using the following syntax:
$phonebook = array();
$phonebook Sally Smart' = '555-9999';
$phonebook John Doe' = '555-1212';
$phonebook J. Random Hacker'= '555-1337';
// or
$phonebook = array(
'Sally Smart' => '555-9999',
'John Doe' => '555-1212',
'J. Random Hacker' => '555-1337',
);
// or, as of PHP 5.4
$phonebook = '555-9999',
'John Doe' => '555-1212',
'J. Random Hacker' => '555-1337',
"> 'Sally Smart' => '555-9999',
'John Doe' => '555-1212',
'J. Random Hacker' => '555-1337',
// or
$phonebook contacts''Sally Smart'] number' = '555-9999';
$phonebook contacts''John Doe'] number' = '555-1212';
$phonebook contacts''J. Random Hacker'] number'= '555-1337';
PHP can loop through an associative array as follows:
foreach ($phonebook as $name => $number)
// For the last array example it is used like this
foreach ($phonebook contacts'as $name => $num)
PHP has an extensive set of functions to operate on arrays.
Associative arrays that can use objects as keys, instead of strings and integers, can be implemented with the
SplObjectStorage
class from the Standard PHP Library (SPL).
Pike
Pike
Pike, Pikes or The Pike may refer to:
Fish
* Blue pike or blue walleye, an extinct color morph of the yellow walleye ''Sander vitreus''
* Ctenoluciidae, the "pike characins", some species of which are commonly known as pikes
* ''Esox'', genus o ...
has built-in support for associative arrays, which are referred to as mappings. Mappings are created as follows:
mapping(string:string) phonebook = ( "Sally Smart":"555-9999",
"John Doe":"555-1212",
"J. Random Hacker":"555-1337"
;
Accessing and testing for presence in mappings is done using the indexing operator. So
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 in the electronic publishing and desktop publishing realm. It is a dynamically typed, concatenative programming language. It was created at Adobe Systems by John Warnock, Charles Geschke, ...
, 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 associated with artificial intelligence and computational linguistics.
Prolog has its roots in first-order logic, a formal logic, and unlike many other programming languages, Prolog is intended primarily a ...
include dictionary ("dict") utilities.
Python
In Python, associative arrays are called " dictionaries". 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
ITerating was a Wiki-based software guide, where users could find, compare and give reviews to software products. As of January 2021 the domain is listed as being for sale and the website no longer on-line. Founded in October 2005, and based in N ...
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 of ...
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 computer programming, object-oriented and Functional programming, functional programming, an immutable object (unchangeable object) is an object (computer science), object whose state cannot be modified after it is created.Goet ...
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–740 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
A 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 sapp ...
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 for ...
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.
Each equivalence relatio ...
) and Hash
(hashability) traits and it stores entries in an unspecified order, and the BTreeMap
requires the Ord
(total order
In mathematics, a total 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 ( reflexiv ...
) 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 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 branches of computer science and linguistics. ...
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 functional programming, a monad is a software design pattern with a structure that combines program fragments ( functions) and wraps their return values in a type with additional computation. In addition to defining a wrapping monadic type, mo ...
in Haskell.
Smalltalk
In Smalltalk
Smalltalk is an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by ...
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 E. Griswold and Ivan P. Polonsky, culminating in SNOBOL4. It was one of ...
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, modular, functional programming language with compile-time type checking and type inference. It is popular among compiler writers and programming language researchers, as well as in the development of ...
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 free and open-source compiler and programming environment for the Standard ML programming language. Aside from its runtime system, which is written in C, SML/NJ is wr ...
(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 with ...
, red–black tree
In computer science, a red–black tree is a kind of self-balancing binary search tree. Each node stores an extra bit representing "color" ("red" or "black"), used to ensure that the tree remains balanced during insertions and deletions.
When the ...
, and splay tree, 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, modular, functional programming language with compile-time type checking and type inference. It is popular among compiler writers and programming language researchers, as well as in the development of the ...
, 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 (now simply referred to as "Visual Basic"), the current version of Visual Basic launched in 2002 which runs on .NET
* Visual Basic (c ...
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, originally called Visual Basic .NET (VB.NET), is a multi-paradigm, object-oriented programming language, implemented on .NET, Mono, and the .NET Framework. Microsoft launched VB.NET in 2002 as the successor to its original Vi ...
uses the collection classes provided by the .NET Framework
The .NET Framework (pronounced as "''dot net"'') is a proprietary software framework developed by Microsoft that runs primarily on Microsoft Windows. It was the predominant implementation of the Common Language Infrastructure (CLI) until bein ...
.
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 interpreter or command-line processor uses a command-line interface (CLI) to receive command (computing), commands from a user in the form of lines of text. This provides a means of setting parameters for the environment, invokin ...
s, Windows PowerShell
PowerShell is a task automation and configuration management program from Microsoft, consisting of a command-line shell and the associated scripting language. Initially a Windows component only, known as Windows PowerShell, it was made open-s ...
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 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 ; also ) is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of attribute–value pairs and arrays (or other s ...
, associative arrays are also referred to as objects. Keys can only be strings.
YAML
YAML
YAML ( and ) (''see '') 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 Ext ...
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