Hashtables [Data Structure]

A hashtable, also known as a dictionary or associative array, is a compact data structure that stores one or more key-value pairs. For example, a hash table might contain a series of IP addresses and computer names, where the IP addresses are the keys and the computer names are the values, or vice versa.

Hashtables are frequently used because they’re efficient for finding and retrieving data.

For example:

Key: Employee ID/SSN to value: Employee name

Key: Serial number to Value: Machine model


Create a hash table and insert key-value pairs:

Hash tables can be created with “@” followed by curly Bracket.

$myHash = @{}

#Follow up with inputting a unique key value with [keyname = x] with x = data string, Integer, statement, etc..
#Key are UNIQUE (Apples,Company,Key)
#Value are not unique (5.5, "Sourcube") 
 
$myHash=@{
Apple=5.5
Company='SourCube'
key=$false
}

Properties of a hash table:

Wrench icon = property, Cube icon = method/function


Show Key:

# Review all the keys stored in the hash table- orders are not sorted
$myhash.Keys

Show Value:

# Prints all the values of the keys
$myhash.Values 

Determine if the hash table has the key or value in there:

Determine if the key or values exist in the hashtable, use the Boolean output to create if conditions if necessary.

#If the key does not exist, it will output false#
$myhash.ContainsKey('key1')

$myhash.ContainsValue(5.5) #Double integers does not need quotation marks#

Get specific values from a key:

$myhash.Apple or $myhash['apple']

$myhash.key1

Add key and values to hashtable:

# Add new key:Pear  value:666 -insert parameters () to the .add method
$myhash.add('key4','666')

#add value with []
$myhash["cherry"] = "this is a string" 

#add key and value with method call
$myhash.grape = 111

Results in unorganized key to value pairing compared to custom objects

Remove key:

$myHash.remove("apple")

Leave a comment