Associative array/Creation: Difference between revisions

Content added Content deleted
(added swift)
Line 1,419: Line 1,419:


=={{header|Nimrod}}==
=={{header|Nimrod}}==
<lang nimrod>
<lang nimrod>import tables
import tables


var
var t: TTable[int,string] = initTable[int,string]()
hash = initTable[string, int]() # empty hash table
hash2 = {"key1": 1, "key2": 2}.toTable # hash table with two keys
hash3 = [("key1", 1), ("key2", 2)].toTable # hash table from tuple array
hash4 = @[("key1", 1), ("key2", 2)].toTable # hash table from tuple seq
value = hash2["key1"]


t[1] = "one"
hash["spam"] = 1
t[2] = "two"
hash["eggs"] = 2
hash.add("foo", 3)
t[3] = "three"
t.add(4,"four")


echo "t has " & $t.len & " elements"
echo "hash has ", hash.len, " elements"
echo "hash has key foo? ", hash.hasKey("foo")
echo "hash has key bar? ", hash.hasKey("bar")


echo "iterate pairs:" # iterating over (key, value) pairs
echo "has t key 4? " & $t.hasKey(4)
for key, value in hash:
echo "has t key 5? " & $t.hasKey(5)
echo key, ": ", value


#iterate keys
echo "iterate keys:" # iterating over keys
echo "key iteration:"
for key in hash.keys:
echo key
for k in t.keys:
echo "at[" & $k & "]=" & t[k]


echo "iterate values:" # iterating over values
#itetate pairs
for key in hash.values:
echo "pair iteration:"
echo key</lang>
for k,v in t.pairs:
echo "at[" & $k & "]=" & v
</lang>
Output:<br/>
Output:<br/>
<pre>
<pre>hash has 3 elements
t has 4 elements
hash has key foo? true
has t key 4? true
hash has key bar? false
iterate pairs:
has t key 5? false
eggs: 2
key iteration:
foo: 3
at[1]=one
spam: 1
at[2]=two
iterate keys:
at[3]=three
eggs
at[4]=four
foo
pair iteration:
spam
at[1]=one
iterate values:
at[2]=two
2
at[3]=three
3
at[4]=four
</pre>
1</pre>


=={{header|Objeck}}==
=={{header|Objeck}}==