Content deleted Content added
→Python: Wikipedia is an encyclopedia, not a how-to guide |
No edit summary |
||
Line 13:
For example:
<syntaxhighlight lang="awk">
phonebook["Sally Smart"] = "555-9999"
phonebook["John Doe"] = "555-1212"
Line 63:
* assigning to the backing property of the indexer, for which the indexer is [[syntactic sugar]] (not applicable to C#, see [[#F#|F#]] or [[#Visual Basic .NET|VB.NET]] examples).
<syntaxhighlight lang=
// Not allowed in C#.
//
</syntaxhighlight>
The dictionary can also be initialized during construction using a "collection initializer", which compiles to repeated calls to <code>Add</code>.
<syntaxhighlight lang=
var
{ "Sally Smart", "555-9999" },
{ "John Doe", "555-1212" },
Line 85:
Values are primarily retrieved using the indexer (which throws an exception if the key does not exist) and the <code>TryGetValue</code> method, which has an output parameter for the sought value and a Boolean return-value indicating whether the key was found.
<syntaxhighlight lang=
var sallyNumber =
</syntaxhighlight>
<syntaxhighlight lang=
var sallyNumber = (
</syntaxhighlight>
In this example, the <code>sallyNumber</code> value will now contain the string <code>"555-9999"</code>.
Line 97:
The following demonstrates enumeration using a [[foreach loop]]:
<syntaxhighlight lang=
// loop through the collection and display each entry.
foreach (KeyValuePair<string,string> kvp in
{
Console.WriteLine("Phone number for {0} is {1}", kvp.Key, kvp.Value);
Line 108:
[[C++]] has a form of associative array called [[map (C++)|<code>std::map</code>]] (see [[Standard Template Library#Containers]]). One could create a phone-book map with the following code in C++:
<syntaxhighlight lang=
#include <map>
#include <string>
Line 122:
Or less efficiently, as this creates temporary <code>std::string</code> values:
<syntaxhighlight lang=
#include <map>
#include <string>
Line 136:
With the extension of [[C++11#Initializer lists|initialization lists]] in C++11, entries can be added during a map's construction as shown below:
<syntaxhighlight lang=
#include <map>
#include <string>
Line 151:
You can iterate through the list with the following code (C++03):
<syntaxhighlight lang=
std::map<std::string, std::string>::iterator curr, end;
for(curr = phone_book.begin(), end = phone_book.end(); curr != end; ++curr)
Line 159:
The same task in C++11:
<syntaxhighlight lang=
for(const auto& curr : phone_book)
std::cout << curr.first << " = " << curr.second << std::endl;
Line 166:
Using the structured binding available in [[C++17]]:
<syntaxhighlight lang=
for (const auto& [name, number] : phone_book) {
std::cout << name << " = " << number << std::endl;
Line 216:
[[D programming language|D]] offers direct support for associative arrays in the core language; such arrays are implemented as a chaining hash table with binary trees.<ref>{{Cite web|title=Associative Arrays - D Programming Language|url=https://dlang.org/spec/hash-map.html|access-date=2021-05-07|website=dlang.org}}</ref> The equivalent example would be:
<syntaxhighlight lang=
int main() {
string[ string ] phone_book;
Line 230:
Looping through all properties and associated values, and printing them, can be coded as follows:
<syntaxhighlight lang=
foreach (key, value; phone_book) {
writeln("Number for " ~ key ~ ": " ~ value );
Line 238:
A property can be removed as follows:
<syntaxhighlight lang=
phone_book.remove("Sally Smart");
</syntaxhighlight>
Line 245:
[[Delphi (programming language)|Delphi]] supports several standard containers, including TDictionary<T>:
<syntaxhighlight lang=
uses
SysUtils,
Line 267:
Versions of Delphi prior to 2009 do not offer direct support for associative arrays. However, associative arrays can be simulated using the TStrings class:
<syntaxhighlight lang=
procedure TForm1.Button1Click(Sender: TObject);
var
Line 298:
Keylists are lists of [[tuple]]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 <code>lists</code> module.
<syntaxhighlight lang=
PhoneBook = [{"Sally Smith", "555-9999"},
{"John Doe", "555-1212"},
Line 306:
Accessing an element of the keylist can be done with the <code>lists:keyfind/3</code> function:
<syntaxhighlight lang=
{_, Phone} = lists:keyfind("Sally Smith", 1, PhoneBook),
io:format("Phone number: ~s~n", [Phone]).
Line 314:
Dictionaries are implemented in the <code>dict</code> module of the standard library. A new dictionary is created using the <code>dict:new/0</code> function and new key/value pairs are stored using the <code>dict:store/3</code> function:
<syntaxhighlight lang=
PhoneBook1 = dict:new(),
PhoneBook2 = dict:store("Sally Smith", "555-9999", Dict1),
Line 323:
Such a serial initialization would be more idiomatically represented in Erlang with the appropriate function:
<syntaxhighlight lang=
PhoneBook = dict:from_list([{"Sally Smith", "555-9999"},
{"John Doe", "555-1212"},
Line 331:
The dictionary can be accessed using the <code>dict:find/2</code> function:
<syntaxhighlight lang=
{ok, Phone} = dict:find("Sally Smith", PhoneBook),
io:format("Phone: ~s~n", [Phone]).
Line 341:
Maps were introduced in OTP 17.0,<ref>{{Cite web|title=Erlang -- maps|url=https://erlang.org/doc/man/maps.html|access-date=2021-03-07|website=erlang.org}}</ref> and combine the strengths of keylists and dictionaries. A map is defined using the syntax <code>#{ K1 => V1, ... Kn => Vn }</code>:
<syntaxhighlight lang=
PhoneBook = #{"Sally Smith" => "555-9999",
"John Doe" => "555-1212",
Line 349:
Basic functions to interact with maps are available from the <code>maps</code> module. For example, the <code>maps:find/2</code> function returns the value associated with a key:
<syntaxhighlight lang=
{ok, Phone} = maps:find("Sally Smith", PhoneBook),
io:format("Phone: ~s~n", [Phone]).
Line 356:
Unlike dictionaries, maps can be pattern matched upon:
<syntaxhighlight lang=
#{"Sally Smith", Phone} = PhoneBook,
io:format("Phone: ~s~n", [Phone]).
Line 363:
Erlang also provides syntax sugar for functional updates—creating a new map based on an existing one, but with modified values or additional keys:
<syntaxhighlight lang=
PhoneBook2 = PhoneBook#{
% the `:=` operator updates the value associated with an existing key
Line 381:
The following example calls the <code>Map</code> 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).
<syntaxhighlight lang="fsharp">
let numbers =
[
Line 393:
Values can be looked up via one of the <code>Map</code> members, such as its indexer or <code>Item</code> property (which throw an [[Exception handling|exception]] if the key does not exist) or the <code>TryFind</code> function, which returns an [[option type]] with a value of <code>Some <result></code>, for a successful lookup, or <code>None</code>, for an unsuccessful one. [[Pattern matching]] can then be used to extract the raw value from the result, or a default value can be set.
<syntaxhighlight lang="fsharp">
let sallyNumber = numbers.["Sally Smart"]
// or
Line 413:
The <code>dict</code> 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 <code>IDictionary<'TKey,'TValue></code>.
<syntaxhighlight lang="fsharp">
let numbers =
[
Line 424:
When a mutable dictionary is needed, the constructor of {{code|System.Collections.Generic.Dictionary<'TKey,'TValue>|f#}} can be called directly. See [[#C#|the C# example on this page]] for additional information.
<syntaxhighlight lang="fsharp">
let numbers = System.Collections.Generic.Dictionary<string, string>()
numbers.Add("Sally Smart", "555-9999")
Line 434:
<code>IDictionary</code> instances have an indexer that is used in the same way as <code>Map</code>, although the equivalent to <code>TryFind</code> is <code>TryGetValue</code>, which has an output parameter for the sought value and a Boolean return value indicating whether the key was found.
<syntaxhighlight lang="fsharp">
let sallyNumber =
let mutable result = ""
Line 441:
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:
<syntaxhighlight lang="fsharp">
let sallyNumber =
match numbers.TryGetValue("Sally Smart") with
Line 476:
Adding elements one at a time:
<syntaxhighlight lang=
phone_book := make(map[string] string) // make an empty map
phone_book["Sally Smart"] = "555-9999"
Line 485:
A map literal:
<syntaxhighlight lang=
phone_book := map[string] string {
"Sally Smart": "555-9999",
Line 495:
Iterating through a map:
<syntaxhighlight lang=
// over both keys and values
for key, value := range phone_book {
Line 510:
The [[Haskell (programming language)|Haskell]] programming language provides only one kind of associative container – a list of pairs:
<syntaxhighlight lang="
m = [("Sally Smart", "555-9999"), ("John Doe", "555-1212"), ("J. Random Hacker", "553-1337")]
Line 524:
One is polymorphic functional maps (represented as immutable balanced binary trees):
<syntaxhighlight lang="
import qualified Data.Map as M
Line 558:
In [[Java (programming language)|Java]] associative arrays are implemented as "maps", which are part of the [[Java collections framework]]. Since [[Java Platform, Standard Edition|J2SE]] 5.0 and the introduction of [[generic programming|generics]] into Java, collections can have a type specified; for example, an associative array that maps strings to strings might be specified as follows:
<syntaxhighlight lang=
Map<String, String> phoneBook = new HashMap<String, String>();
phoneBook.put("Sally Smart", "555-9999");
Line 573:
For two objects ''a'' and ''b'',
<syntaxhighlight lang=
a.equals(b) == b.equals(a)
if a.equals(b), then a.hashCode() == b.hashCode()
Line 594:
A map can be initialized with all items during construction:
<syntaxhighlight lang=
const phoneBook = new Map([
["Sally Smart", "555-9999"],
Line 604:
Alternatively, you can initialize an empty map and then add items:
<syntaxhighlight lang=
const phoneBook = new Map();
phoneBook.set("Sally Smart", "555-9999");
Line 614:
Accessing an element of the map can be done with the <code>get</code> method:
<syntaxhighlight lang=
const sallyNumber = phoneBook.get("Sally Smart");
</syntaxhighlight>
Line 623:
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:
<syntaxhighlight lang=
// loop through the collection and display each entry.
for (const [name, number] of phoneBook) {
Line 632:
A key can be removed as follows:
<syntaxhighlight lang=
phoneBook.delete("Sally Smart");
</syntaxhighlight>
Line 643:
An object literal is written as <code>{ property1: value1, property2: value2, ... }</code>. For example:
<syntaxhighlight lang=
const myObject = {
"Sally Smart": "555-9999",
|